JavaScript 显示精确到小数点后两位的浮点数

发布于 2024-09-08 02:46:27 字数 295 浏览 1 评论 0原文

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

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

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

请在 JSbin 上查看。

最好的方法是什么?

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

I wanted to display a number to 2 decimal places.

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

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

See it on 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

尐籹人 2024-09-15 02:46:27
float_num.toFixed(2);

注意:toFixed()将舍入或用零填充。

float_num.toFixed(2);

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

記憶穿過時間隧道 2024-09-15 02:46:27

您可以使用 toFixed 函数来完成此操作,但它在 IE 中存在错误。如果您想要可靠的解决方案,请在此处查看我的答案

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

甜`诱少女 2024-09-15 02:46:27

使用 toFixed 您可以像这样设置小数点长度:

let number = 6.1234
number.toFixed(2) // '6.12'

但是 toFixed 返回一个字符串,并且如果 number 根本没有小数点它会添加多余的零。

let number = 6
number.toFixed(2) // '6.00'

为了避免这种情况,您必须将结果转换为数字。你可以用这两种方法来做到这一点:

let number1 = 6
let number2 = 6.1234

// method 1
parseFloat(number1.toFixed(2)) // 6
parseFloat(number2.toFixed(2)) // 6.12

// method 2
+number1.toFixed(2) // 6
+number2.toFixed(2) // 6.12

with toFixed you can set length of decimal points like this:

let number = 6.1234
number.toFixed(2) // '6.12'

but toFixed returns a string and also if number doesn't have decimal point at all it will add redundant zeros.

let number = 6
number.toFixed(2) // '6.00'

to avoid this you have to convert the result to a number. you can do this with these two methods:

let number1 = 6
let number2 = 6.1234

// method 1
parseFloat(number1.toFixed(2)) // 6
parseFloat(number2.toFixed(2)) // 6.12

// method 2
+number1.toFixed(2) // 6
+number2.toFixed(2) // 6.12
默嘫て 2024-09-15 02:46:27

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

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

Math.round(number * 100) / 100

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

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

Math.round(number * 100) / 100

洋洋洒洒 2024-09-15 02:46:27

不知道我是如何想到这个问题的,但即使这个问题已经问了很多年了,我想添加一个我遵循的快速而简单的方法,它从未让我失望:

var num = response_from_a_function_or_something();

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

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 );
夏の忆 2024-09-15 02:46:27

尝试 toFixed 而不是 toPrecision

Try toFixed instead of toPrecision.

混吃等死 2024-09-15 02:46:27

函数round(值,小数){
return Number(Math.round(值+'e'+小数)+'e-'+小数);
}

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

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

答案如下: http://www. jacklmoore.com/notes/rounding-in-javascript/

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

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

摘星┃星的人 2024-09-15 02:46:27

如果你需要 2 位数字而不是字符串类型,我就用这种方法。

    const exFloat = 3.14159265359;
    
    console.log(parseFloat(exFloat.toFixed(2)));

I used this way if you need 2 digits and not string type.

    const exFloat = 3.14159265359;
    
    console.log(parseFloat(exFloat.toFixed(2)));
清醇 2024-09-15 02:46:27

您可以尝试混合使用 Number()toFixed()

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

Number( (myVar).toFixed(2) )


请参阅下面的示例:

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>

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

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

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>

幻梦 2024-09-15 02:46:27

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

这里的语法

numObj.toFixed([digits])

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

numObj.toFixed([digits]) * 1

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

这里是 完整详细信息以及浏览器中的兼容性。

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

and here is the syntax

numObj.toFixed([digits])

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

numObj.toFixed([digits]) * 1

It also can throws exceptions like TypeError, RangeError

Here is the full detail and compatibility in the browser.

贪恋 2024-09-15 02:46:27
let a = 0.0500
a.toFixed(2);

//output
0.05
let a = 0.0500
a.toFixed(2);

//output
0.05
终止放荡 2024-09-15 02:46:27

还有 Intl API 可根据您的区域设置值设置小数格式。如果小数点分隔符不是点“.”,这一点尤其重要。而是用逗号“,”代替,就像德国的情况一样。

Intl.NumberFormat('de-DE').formatToParts(0.05).reduce((acc, {value}) => acc += value, '');

请注意,这将最多四舍五入到小数点后 3 位,就像上面默认情况下建议的 round() 函数一样。如果您想自定义该行为以指定小数位数,可以选择最小和最大小数位数:

Intl.NumberFormat('de-DE', {minimumFractionDigits: 3}).formatToParts(0.05)

There's also the Intl API to format decimals according to your locale value. This is important specially if the decimal separator isn't a dot "." but a comma "," instead, like it is the case in Germany.

Intl.NumberFormat('de-DE').formatToParts(0.05).reduce((acc, {value}) => acc += value, '');

Note that this will round to a maximum of 3 decimal places, just like the round() function suggested above in the default case. If you want to customize that behavior to specify the number of decimal places, there're options for minimum and maximum fraction digits:

Intl.NumberFormat('de-DE', {minimumFractionDigits: 3}).formatToParts(0.05)
放手` 2024-09-15 02:46:27
float_num = parseFloat(float_num.toFixed(2))
float_num = parseFloat(float_num.toFixed(2))
递刀给你 2024-09-15 02:46:27

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

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

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文