假设我有一个值15.7784514,我想显示它15.77时不进行舍入。
var num = parseFloat(15.7784514);
document.write(num.toFixed(1)+"<br />");
document.write(num.toFixed(2)+"<br />");
document.write(num.toFixed(3)+"<br />");
document.write(num.toFixed(10));
结果是-
15.8
15.78
15.778
15.7784514000
如何显示15.77?
发布于 2010-11-16 01:33:29
将数字转换为字符串,将数字匹配到小数点后第二位:
function calc(theform) {
var num = theform.original.value, rounded = theform.rounded
var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]
rounded.value = with2Decimals
}
<form onsubmit="return calc(this)">
Original number: <input name="original" type="text" onkeyup="calc(form)" onchange="calc(form)" />
<br />"Rounded" number: <input name="rounded" type="text" placeholder="readonly" readonly>
</form>
与toString
不同,toFixed
方法在某些情况下会失败,因此要非常小心地使用它。
发布于 2012-10-10 09:34:28
我选择这样写,而不是手动删除字符串的余数,这样我就不必处理数字带来的数学问题:
num = num.toString(); //If it's not already a String
num = num.slice(0, (num.indexOf("."))+3); //With 3 exposing the hundredths place
Number(num); //If you need it back as a Number
这将给你"15.77“,num = 15.7784514;
发布于 2018-01-05 00:54:26
另一个单行解决方案:
number = Math.trunc(number*100)/100
我使用100,因为您希望截断到第二位,但更灵活的解决方案是:
number = Math.trunc(number*Math.pow(10, digits))/Math.pow(10, digits)
其中digits是要保留的十进制位数。
有关详细信息和浏览器兼容性,请参阅Math.trunc specs。
https://stackoverflow.com/questions/4187146
复制相似问题