JavaScript 显示一个浮点数到 2 个小数位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3163070/
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 03:30:02  来源:igfitidea点击:

JavaScript displaying a float to 2 decimal places

javascriptfloating-pointprecision

提问by alex

I wanted to display a number to 2 decimal places.

我想显示一个数字到小数点后两位。

I thought I could use toPrecision(2)in JavaScript .

我以为我可以toPrecision(2)在 JavaScript 中使用。

However, if the number is 0.05, I get 0.0500. I'd rather it stay the same.

但是,如果数字是0.05,我会得到0.0500。我宁愿它保持不变。

See it on JSbin.

JSbin上看到它。

What is the best way to do this?

做这个的最好方式是什么?

I can think of coding a few solutions, but I'd imagine (I hope) something like this is built in?

我可以考虑编写一些解决方案,但我想(我希望)内置了这样的东西?

回答by Jason McCreary

float_num.toFixed(2);

Note:toFixed()will round or pad with zeros if necessary to meet the specified length.

注意:toFixed()如有必要,将舍入或填充零以满足指定的长度。

回答by Elias Zamaria

You could do it with the toFixedfunction, but it's buggy in IE. If you want a reliable solution, look at my answer here.

你可以用这个toFixed函数来做,但它在 IE 中有问题。如果您想要一个可靠的解决方案,请在此处查看我的回答。

回答by casablanca

Try toFixedinstead of toPrecision.

尝试toFixed代替toPrecision.

回答by panos

Don't know how I got to this question, but even if it's many years since this has been asked, I would like to add a quick and simple method I follow and it has never let me down:

不知道我是怎么想到这个问题的,但即使自从问这个问题已经很多年了,我想添加一个我遵循的快速简单的方法,它从来没有让我失望:

var num = response_from_a_function_or_something();

var fixedNum = parseFloat(num).toFixed( 2 );

回答by Huy Nguyen

function round(value, decimals) { return Number(Math.round(value+'e'+decimals)+'e-'+decimals); }

function round(value, decimals) { return Number(Math.round(value+'e'+decimals)+'e-'+decimals); }

round(1.005, 2); // return 1.01

round(1.004, 2); // return 1 instead of 1.00

回合(1.005, 2); // 返回 1.01

回合(1.004, 2); // 返回 1 而不是 1.00

The answer is following this link: http://www.Hymanlmoore.com/notes/rounding-in-javascript/

答案是以下链接:http: //www.Hymanlmoore.com/notes/rounding-in-javascript/

回答by rnmalone

number.parseFloat(2)works but it returns a string.

number.parseFloat(2)有效,但它返回一个字符串。

If you'd like to preserve it as a number type you can use:

如果您想将其保留为数字类型,您可以使用:

Math.round(number * 100) / 100

Math.round(number * 100) / 100

回答by George-Paul B.

You could try mixing Number()and toFixed().

你可以尝试混合Number()toFixed()

Have your target number converted to a nice string with X digits then convert the formated string to a number.

将您的目标数字转换为带有 X 位数字的漂亮字符串,然后将格式化的字符串转换为数字。

Number( (myVar).toFixed(2) )

Number( (myVar).toFixed(2) )



See example below:

请参阅下面的示例:

var myNumber = 5.01;
var multiplier = 5;
$('#actionButton').on('click', function() {
  $('#message').text( myNumber * multiplier );
});

$('#actionButton2').on('click', function() {
  $('#message').text( Number( (myNumber * multiplier).toFixed(2) ) );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button id="actionButton">Weird numbers</button>
<button id="actionButton2">Nice numbers</button>

<div id="message"></div>

回答by Sunil Garg

The toFixed()method formats a number using fixed-point notation.

toFixed()方法使用定点表示法格式化数字。

and here is the syntax

这是语法

numObj.toFixed([digits])

digitsargument is optional and by default is 0. And the return type is string not number. But you can convert it to number using

数字参数是可选的,默认为 0。返回类型是字符串而不是数字。但是您可以使用将其转换为数字

numObj.toFixed([digits]) * 1

It also can throws exceptions like TypeError, RangeError

它还可以抛出异常,例如TypeErrorRangeError

Here is the full detailand compatibility in the browser.

这是浏览器中的完整细节和兼容性。

回答by Rizo

let a = 0.0500
a.toFixed(2);

//output
0.05

回答by Syed Nurul Islam

I have made this function. It works fine but returns string.

我做了这个功能。它工作正常,但返回字符串。

function show_float_val(val,upto = 2){
  var val = parseFloat(val);
  return val.toFixed(upto);
}