我想格式化我的数字,总是显示2小数点后,四舍五入适用的地方。

例子:

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

我一直在用这个:

parseFloat(num).toFixed(2);

但是它把1显示为1,而不是1.00。


当前回答

如果value = 1.005,此回答将失败。

作为一个更好的解决方案,可以使用指数表示的数字来避免舍入问题:

Number(Math.round(1.005+'e2')+'e-2'); // 1.01

@Kon和原作者建议的更简洁的代码:

Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces)

你可以在末尾加上toFixed()以保留小数点,例如:1.00,但注意它将返回字符串。

Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces).toFixed(decimalPlaces)

来源:JavaScript中的四舍五入小数

其他回答

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

变量数= 123456.789; console.log(纽约肯尼迪机场。NumberFormat(’en-IN’} maximumFractionDigits: 2 })的葡萄酒种植区(编号);

一个更通用的N位舍入解决方案

function roundN(num,n){
  return parseFloat(Math.round(num * Math.pow(10, n)) /Math.pow(10,n)).toFixed(n);
}


console.log(roundN(1,2))
console.log(roundN(1.34,2))
console.log(roundN(1.35,2))
console.log(roundN(1.344,2))
console.log(roundN(1.345,2))
console.log(roundN(1.344,3))
console.log(roundN(1.345,3))
console.log(roundN(1.3444,3))
console.log(roundN(1.3455,3))

Output

1.00
1.34
1.35
1.34
1.35
1.344
1.345
1.344
1.346

如果你已经在使用jQuery,你可以看看如何使用jQuery数字格式插件。

该插件可以返回格式化的数字作为字符串,你可以设置小数,和千位分隔符,你可以选择显示的小数的数量。

$.number( 123, 2 ); // Returns '123.00'

你也可以从GitHub获得jQuery数字格式。

如果value = 1.005,此回答将失败。

作为一个更好的解决方案,可以使用指数表示的数字来避免舍入问题:

Number(Math.round(1.005+'e2')+'e-2'); // 1.01

@Kon和原作者建议的更简洁的代码:

Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces)

你可以在末尾加上toFixed()以保留小数点,例如:1.00,但注意它将返回字符串。

Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces).toFixed(decimalPlaces)

来源:JavaScript中的四舍五入小数

<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>


<input type="text" class = 'item_price' name="price" min="1.00" placeholder="Enter Price" value="{{ old('price') }}" step="">

<script> 
$(document).ready(function() {
    $('.item_price').mask('00000.00', { reverse: true });
});
</script>