How to multiply in Javascript? problems with decim

2020-02-18 21:13发布

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?

13条回答
一纸荒年 Trace。
2楼-- · 2020-02-18 21:33

Just try

var x = 0.07;
console.log((x+1)*100 - 100);

now, replace the value of x for the other values ;-)

查看更多
姐就是有狂的资本
3楼-- · 2020-02-18 21:34

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.

function decimalPlaces(num) {
    var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
    if (!match) { return 0; }
    return Math.max(
        0,
        // Number of digits right of decimal point.
        (match[1] ? match[1].length : 0)
        // Adjust for scientific notation.
        - (match[2] ? +match[2] : 0));
}

And then for your final answer "total" you do

total = total.toFixed(decimalPlaces(a)+decimalPlaces(b));

where a,b are your numbers

查看更多
ゆ 、 Hurt°
4楼-- · 2020-02-18 21:36

.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
查看更多
Juvenile、少年°
5楼-- · 2020-02-18 21:36

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+$/,'');

查看更多
男人必须洒脱
6楼-- · 2020-02-18 21:37

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:

查看更多
Juvenile、少年°
7楼-- · 2020-02-18 21:39

I ended up with the following solution:

function decimalmultiply(a, b) {
    return parseFloat((a * b).toFixed(12));
}

10.50*30.45=319.72499999999997
decimalmultiply(10.50,30.45)=319.725

This method returns a number, not a string, without truncating significant decimals (up to 12).

查看更多
登录 后发表回答