i've the following code in Javascript:
var m1 = 2232.00;
var percent = (10/100);
var total = percent*m1;
alert(total);
The problem is that the variable "total" gives me "223.20000000000002" and it should be "223.2", what should i do to get the correct value?
Just try
now, replace the value of x for the other values ;-)
Here is a work around solution for multiplication of floating numbers. It's pretty simple but works for me. You figure out how many decimals the numbers have with this function.
And then for your final answer "total" you do
where a,b are your numbers
.toFixed() is best solution.It will keep only two digits after dot.
Exp 1:
Exp 2:
You can't get the exact value. This is the fundamental problem with floating-point numbers.
You can force a fixed number of decimal numbers with
toFixed
:However, keep in mind that this will leave trailing zeroes, which you might not want. You can remove them with
.replace(/0+$/,'');
I found the answer using the following pages, thanks to Dimitry:
Floating-point cheat sheet for JavaScript
I decided to use the following clases because i need the exact values of the operations and they're related to money operations:
I ended up with the following solution:
This method returns a number, not a string, without truncating significant decimals (up to 12).