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?
To multiply decimals, first multiply as if there is no decimal. Next, count the number of digits after the decimal in each factor. Finally, put the same number of digits behind the decimal in the product.
Multiplication and division operators are also available in JavaScript, and are used to find the product and quotient of numerical values. An asterisk ( * ) is used to represent the multiplication operator.
JavaScript has only one type of number. Numbers can be written with or without decimals.
But it can also be tricky if you are trying to multiply 2 decimal numbers that are coming from 2 different input fields. Almost in every programming language, we have a multiplication operator ( *) to multiply one number to another and it is also present in javascript.
But why is that? In JavaScript all numbers are IEEE 754 floating point numbers. Due to the binary nature of their encoding, some decimal numbers cannot be represented with perfect accuracy. This is analagous to how the fraction 1/3 cannot be accurately represented with a decimal number with a finite number of digits.
Of course, this doesn't solve all problems. Division of integers and multiplication by decimals may still result in inexact values, but basic integer addition, subtraction, and multiplication will be accurate. (At least until you hit JavaScript's upper limit for numbers.)
This happens because Javascript treats all of its numbers as floating point numbers, and their binary math cannot exactly represent numbers which has denominator not divisible by 2. See this excellent StackOverFlow post for an explanation. And, see this by the author of the selected answer. Binary floating point math is like this.
.toFixed() is best solution.It will keep only two digits after dot.
Exp 1:
var value = 3.666; value.toFixed(2); //Output : 3.67
Exp 2:
var value = 3.0000; value.toFixed(2); //Output : 3.00
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
:
alert(total.toFixed(2));
However, keep in mind that this will leave trailing zeroes, which you might not want. You can remove them with .replace(/0+$/,'');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With