Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript adding decimal numbers issue [duplicate]

So I am making a script that adds two numbers (decimal numbers) together, which I have encountered a problem.

http://jsfiddle.net/DerekL/esqnC/

I made the script, it turns out pretty good:

0.1 + 0.5  //0.6 0.2 + 0.3  //0.5 

But soon I see:

0.1 + 0.2  //0.30000000000000004 0.01 + 0.06  //0.06999999999999999 

And it does not look right to me. I know it is a shortcoming of using float point with finite bits, but I can't find a way to fix that.

Math.ceil   //No Math.floor  //No .slice      //No 

UPDATE

Is it possible to multiply the numbers by 1000 first, then add them then divide it by 1000?

like image 432
Derek 朕會功夫 Avatar asked May 06 '12 20:05

Derek 朕會功夫


People also ask

Why does adding two decimals in JavaScript produce a wrong result?

Because internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.

How do you force decimals in JavaScript?

The toFixed() method converts a number to a string. The toFixed() method rounds the string to a specified number of decimals.

How do I fix 2dp?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.

How do I force two decimal places in JavaScript?

STEP 1 − Declare a variable named “num” and assign a number to the variable. STEP 2 − Compute num. toFixed(2). The result is formatted with two decimals.


1 Answers

Use toFixed to convert it to a string with some decimal places shaved off, and then convert it back to a number.

+(0.1 + 0.2).toFixed(12) // 0.3 

It looks like IE's toFixed has some weird behavior, so if you need to support IE something like this might be better:

Math.round((0.1 + 0.2) * 1e12) / 1e12 
like image 102
Dagg Nabbit Avatar answered Oct 01 '22 00:10

Dagg Nabbit