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?
total.toFixed(2)
may help. But note that thetotal
variable be will typecasted into a string.This can be done well with an external library called decimal.js that provides a
Decimal
type for JavaScript. It's also available for Node on npm. Below is an example that replicates the original example from gustavomanolo using decimal.js.If you are trying to display this number, you could convert to a string with toFixed(1). If you do this, keep track of the types because you can't then multiply the string with another number.
If you are going to use it in another computation you could truncate it to one decimal place:
However, as pointed out by various people, the inexact value is just the way floating point numbers are.
See the questions linked in the comments for more good information.
I found a very simple solution. The
*
operator is a bit broken when it comes to decimal numbers, but the/
operator is not. A multiplication can be easily transformed into a division since a • b = a / (1/b)Just replace
percent * m1
withtimes(percent, m1)
.Update: It doesn't work all the times.
The operator "*" and "/" do not work perfectly always, for example:
Solution:
One solution, the easy one, to have decimals is useing .toFixed(2) where "2" is the number of decimal digits that you want. But you have to take into account this return you a String, and it rounds the value.
Other option, the most complete, is using .toLocaleString that converts the number properly to the country code that you want. You can set a pair of params to fix the decimals values always to 2. This also returns you a String:
If you need it as a Number, you can wrap it into Number( ... ) :
If you only want a no decimal number, use one of this methods to be sure that the result is without decimals.
If you are using Angular, I made a component for this.
Install with bower
Usage
Try it yourself with this snippet below.