Rounding number to two decimal places

2019-07-27 00:46发布

问题:

Hy guys, I have a case where a want to round the number to exactly two decimal places. I will give an example and what I tried.

Lets say I have 15.07567 To round it up I did:

price = Math.round(15.07567 * 100) / 100;

// and I get 15.08

But this presents a problems if we have digits that end wit 0 (example 15.10) and we want two decimals.

price = Math.round(15.10 * 100) / 100;

//15.1

Hmmm, so I tried to use toFixed()

price = Math.round(15.10 * 100) / 100;
total = price.toFixed(2);

// I get "15.10", that's good but it returns a string and that could present a problem later on for me so I tried to fix this with:

price = Math.round(15.10 * 100) / 100;
total = price.toFixed(2);
Number(total)  //or  parseFloat(total)

// I get 15.1 and around in circle I go?

回答1:

As Jordan said. When JavaScript displays the number it'll drop the 0. I'd just store the value as is and when you display it, run it through the .toFixed(2) so that it displays properly. Or even better, find a currency formatter since that seems to be what you're looking to display and use that on the view side.

Here's a nice currency formating script.

Number.prototype.formatMoney = function(c, d='.', t=','){
    var n = this, 
    c = isNaN(c = Math.abs(c)) ? 2 : c, 
    d = d == undefined ? "." : d, 
    t = t == undefined ? "," : t, 
    s = n < 0 ? "-" : "", 
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", 
    j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

Then you can use it an object oriented fashion with this code:

price.formatMoney(2);

Or if you want to specify the thousands and decimal separators for Europe.

price.formatMoney(2, ',', '.');


回答2:

If you want to show the 0 in the right, you need to represent the number in String...



回答3:

Always keep your numbers, when you display them run them through toFixed to get a desired display format, so you'll have a ready value in a string format. Because the method is required and therefore designed for display purposes, the function returns a ready string instead of a number.