Format number to always show 2 decimal places

2018-12-31 03:15发布

I would like to format my numbers to always display 2 decimal places, rounding where applicable.

Examples:

number     display
------     -------
1          1.00
1.341      1.34
1.345      1.35

I have been using this:

parseFloat(num).toFixed(2);

But it's displaying 1 as 1, rather than 1.00.

26条回答
荒废的爱情
2楼-- · 2018-12-31 03:32

here is another solution to round only using floor, meaning , making sure calculated amount won't be bigger than original amount (sometimes needed for transactions): Math.floor(num* 100 )/100

查看更多
孤独寂梦人
3楼-- · 2018-12-31 03:34
var num = new Number(14.12);
console.log(num.toPrecision(2));//outputs 14
console.log(num.toPrecision(3));//outputs 14.1
console.log(num.toPrecision(4));//outputs 14.12
console.log(num.toPrecision(5));//outputs 14.120
查看更多
孤独总比滥情好
4楼-- · 2018-12-31 03:36
var number = 123456.789;


console.log(new Intl.NumberFormat('en-IN', { maximumFractionDigits: 2 }).format(number));

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

查看更多
高级女魔头
5楼-- · 2018-12-31 03:36

function number_format(string,decimals=2,decimal=',',thousands='.',pre='R$ ',pos=' Reais'){
  var numbers = string.toString().match(/\d+/g).join([]);
  numbers = numbers.padStart(decimals+1, "0");
  var splitNumbers = numbers.split("").reverse();
  var mask = '';
  splitNumbers.forEach(function(d,i){
    if (i == decimals) { mask = decimal + mask; }
    if (i>(decimals+1) && ((i-2)%(decimals+1))==0) { mask = thousands + mask; }
    mask = d + mask;
  });
  return pre + mask + pos;
}
var element = document.getElementById("format");
var money= number_format("10987654321",2,',','.');
element.innerHTML = money;
#format{
display:inline-block;
padding:10px;
border:1px solid #ffffd;
background:#f5f5f5;
}
<div id='format'>Test 123456789</div>

查看更多
旧时光的记忆
6楼-- · 2018-12-31 03:38

Are you looking for floor?

var num = 1.42482;
var num2 = 1;
var fnum = Math.floor(num).toFixed(2);
var fnum2 = Math.floor(num2).toFixed(2);
alert(fnum + " and " + fnum2); //both values will be 1.00
查看更多
看淡一切
7楼-- · 2018-12-31 03:38

Here's also a generic function that can format to any number of decimal places:

function numberFormat(val, decimalPlaces) {

    var multiplier = Math.pow(10, decimalPlaces);
    return (Math.round(val * multiplier) / multiplier).toFixed(decimalPlaces);
}
查看更多
登录 后发表回答