javascript 如何在没有科学计数法的情况下显示“toPrecision”的结果?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4689142/
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
How to display the result of "toPrecision" without the scientific notation?
提问by Ricky
Based on http://www.mredkj.com/javascript/nfbasic2.html, following code will result in 5.6e+2.
基于http://www.mredkj.com/javascript/nfbasic2.html,以下代码将导致5.6e+2。
num = 555.55;
result = num.toPrecision(2); // result will equal 5.6e+2
How can I let the output of the result variable be displayed without scientific notation(i.e., e)?
如何让结果变量的输出在没有科学计数法(即e)的情况下显示?
采纳答案by Sebastian Paaske T?rholm
To get a float with reduced precision, you could use toPrecision()like you do, and then parse the scientific notation with parseFloat(), like so:
要获得精度降低的浮点数,您可以toPrecision()像这样使用,然后使用parseFloat()解析科学记数法,如下所示:
result = parseFloat(num.toPrecision(2));
If you do not wish to reduce precision, you could use toFixed()to get the number with a certain number of decimals.
如果您不想降低精度,您可以使用toFixed()来获取具有一定小数位数的数字。
回答by Tolgahan Albayrak
回答by Zaje
Try
尝试
result = Math.ceil(555.55);
回答by garlon4
I had a similar desire to preserve a certain amount of precision, not have trailing zeros, and not have scientific notation. I think the following function works:
我也有类似的愿望,希望保持一定的精度,没有尾随零,也没有科学记数法。我认为以下功能有效:
function toDecimalPrecision(val, digits) {
val = (+val).toPrecision(digits);
if (val.indexOf('e') >= 0) {
val = (+val).toString();
} else if (val.indexOf('.') >= 0) {
val = val.replace(/(\.|)0+$/, '');
}
return val;
回答by timdream
evalis evil.
eval是邪恶的。
Do
做
var result = num.toPrecision(2).toString(10);
var result = num.toPrecision(2).toString(10);
instead.
反而。

