Link to home
Start Free TrialLog in
Avatar of joomla
joomlaFlag for Australia

asked on

javascript subtract to dollar values

$a = document.getElementByID('dollar1');  //  returns $2,000,000.50;
$b = document.getElementByID('dollar2');  //  returns $1,000,000.10;

How do I get $a - $b to return $1,000,000.40;

I've tried parseFloat($a) - parseFloat($b)
I've tried parseFloat($a.replace('$', '')) - parseFloat($a.replace('$', ''))

thanks
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Like this...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>JS Math</title>
</head>
<body>
<h1>JS Math</h1>
<script type="text/javascript">
<!--
var d1 = 2000000.50;
var d2 = 1000000.10;
document.write(d1.toFixed(2)+"<br>");
document.write(d2.toFixed(2)+"<br>");
var d3;
d3 = d1-d2;
document.write(d3.toFixed(2)+"<br>");

// -->
</script>
</body>
</html>

Open in new window

Avatar of joomla

ASKER

sorry, I don't understand what you're suggesting.

I have a form with two three fields
If I enter the value $2,000,0000.50 into field called "dollar1"
and
enter the value $1,000,000.10 into a field called "dollar2"

I want an onchange routine in field "dollar2" to populate a field called "dollar3"
with the value $1,000,000.40

thanks
The reason you don't often see numbers formatted like that is that javascript doesn't understand the commas ','.  If you enter numbers that way, you have to strip off the '$' and the ',' before you try to do the math or it won't work.  Then to display the result that way, you have to add those back into the result.
Avatar of joomla

ASKER

thanks,
i'm sorry to be ackward, but I did try strip the $ and the , from the numbers but keep getting an error.

can you suggest a work reg pattern ?
Avatar of aplusexpert
aplusexpert

Try this script.

<script type="text/javascript">
function getVal(){

var dollar1= parseInt(document.getElementById('dollar1').value.replace('$', ''));
var doller2= parseInt(document.getElementById('dollar2').value.replace('$', ''));

var ans= doller1- doller2;

alert(output);
}
</script>

Open in new window


I think this may helps you.
If not then refer this link
http://www.webdeveloper.com/forum/showthread.php?t=189831

Thanks...
ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial