Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

why is 0.10 * 3 = 0.30000000004? can't figure out why it's not .30!!!

Status
Not open for further replies.

spewn

Programmer
May 7, 2001
1,034

i have a shopping cart that i am trying to debug. it seems that it works except with certain amounts. upon investigation, i noticed that when multiplied together, the result is below:

Code:
num1=0.10;
num2=3;
num3=num1*num2;
//num3 now equals 0.30000000004.

anyone know why this is?

- g
 
From what I've read, specifically this article, it sounds like its just a bug.

to work around it you could just use something like this:
Code:
num1=0.10;
num2=3;
num3=(num1*num2).toFixed(2);

hope that helps

"Insane people are always sure that they are fine. It is only the sane people who are willing to admit that they are crazy." - Nora Ephron
 

ok, this 'fix' only cuts the trailing numbers after the decimal, in this case after 2. but it doesn't give me a number that was rounded.

for instance...

i have 3.1456 and i use the toFixed(2), it will give me 3.14 instead of 3.15.

the problem i am having is an issue where the rounding off is not occurring. i am writing a script in perl to produce a figure based the addition/multiplication of other figures. once on screen, i am allowing the user to manipulate the totals dynamically (hence, javascript). however, this issue with not rounding off is causing inconsistencies in the addition of the figures.

it just doesn't look right.

any ideas?

- g
 
What I've done to take care of this problem is multiply by 100, then round and divide by 100. I've seen other ways that work as well.

Code:
function formatdollar(oneamount)
{
if (isNaN(oneamount)) return 'NaN';

if ((oneamount * 1) == 0) return '0.00';
var newamount=Math.round(oneamount * 100) + '';
if (newamount < 10) newamount = '0' + newamount;
newamount = newamount.substr(0, newamount.length-2) + '.' + newamount.substr(newamount.length-2);
return newamount;
}

Lee
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top