在 javascript/jquery 中四舍五入到 3 个小数点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33429136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:02:36  来源:igfitidea点击:

round to 3 decimal points in javascript/jquery

javascript

提问by Sanju Menon

How will i round margin_total to 3 decimal places?

我如何将 margin_total 舍入到小数点后三位?

margin_total = margin_total + parseFloat(marginObj.value);
document.getElementById('margin_total').value = margin_total;

回答by Paul S.

Use num.toFixed(d)to convert a number into the String representationof that number in base 10with ddigitsafter the decimal point, in this case,

使用num.toFixed(d)将数字转换成字符串表示该数量的在基座10d小数点后,在这种情况下,

margin_total.toFixed(3);

回答by Rayon

The toFixed()method converts a number into a string, keeping a specified number of decimals. A string representation of input that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.

toFixed()方法将数字转换为字符串,并保留指定的小数位数。输入的字符串表示形式,不使用指数表示法,并且在小数位后具有精确的数字。如有必要,数字会四舍五入,并在必要时用零填充小数部分,使其具有指定的长度。

function myFunction() {
  var num = 5.56789;
  var n = num.toFixed(3)
  document.getElementById("demo").innerHTML = n;
}
<p>Click the button to display the fixed number.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

回答by Nditah

const num = 70.012345678900
console.log(parseFloat(num.toFixed(3)));
// expected output: 70.012