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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with calculation in javascript 2

Status
Not open for further replies.

Petal

Programmer
Jun 8, 2001
56
0
0
NO
Hi

I have made a simple calculator. It works almost as it should except with multiplying with decimals.
When I try to multiply: 0.1*2.8 i got the result 0.27999999999999997 . It should be 2.8.

Here is my code:
function regnut() {
fotm.maks.value=0.1*2.8;
}

Have anybody hade a similar problem?

Jørn Arild Andenæs
jaa@jaa.no
 
I fined the solution by myself. I used:

maks.value=Math.round((0,1*2,8)*1000)/1000;

Jørn Arild Andenæs
jaa@jaa.no
 
It has to do with how decimals are stored. Their stored as a whole number and a separate fractional number. Unfortunately some numbers can't be properly represented. Kind of like 1/3. Writing .3333 is not accurate but it is a close approximation.

Take a look in a reference manual - there may be a function to correct for this inherent problem. Another way is to use rounding. BTW, this is not a problem with JavaScript per se. Every language I've ever used has this problem to some degree or another. It all comes down to how they choose to store numbers, but with any scheme there will always be some measure of precision loss.

Scott
 
That gives me a zero ???

In javascript 1.5 you can use:

maks.value=(0.1*2.8).toFixed(2);

Hope this helps,
Erik

<!-- My sport: Boomerang throwing !!
This year I will participate at the World Championships in Germany. (!! Many Happy Returns !! -->
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top