简体   繁体   English

JavaScript 将浮点数显示为小数点后两位

[英]JavaScript displaying a float to 2 decimal places

I wanted to display a number to 2 decimal places.我想显示一个数字到小数点后两位。

I thought I could use toPrecision(2) in JavaScript.我想我可以在 JavaScript 中使用toPrecision(2)

However, if the number is 0.05 , I get 0.0500 .但是,如果数字是0.05 ,我得到0.0500 I'd rather it stay the same.我宁愿它保持不变。

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?我可以考虑编写一些解决方案,但我想(我希望)内置这样的东西?

float_num.toFixed(2);

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

You could do it with the toFixed function, but it's buggy in IE .你可以用toFixed函数来做,但它在 IE 中有问题 If you want a reliable solution, look at my answer here .如果您想要一个可靠的解决方案,请在此处查看我的回答。

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 );

尝试toFixed而不是toPrecision

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

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

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

round(1.004, 2);回合(1.004, 2); // return 1 instead of 1.00 // 返回 1 而不是 1.00

The answer is following this link: http://www.jacklmoore.com/notes/rounding-in-javascript/答案是以下链接: http : //www.jacklmoore.com/notes/rounding-in-javascript/

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) )


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>

let a = 0.0500
a.toFixed(2);

//output
0.05

The toFixed() method formats a number using fixed-point notation. toFixed()方法使用定点表示法格式化数字。

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.数字参数是可选的,默认为 0。返回类型是字符串而不是数字。 But you can convert it to number using但是您可以使用将其转换为数字

numObj.toFixed([digits]) * 1

It also can throws exceptions like TypeError , RangeError它还可以抛出TypeErrorRangeErrorTypeError

Here is the full detail and compatibility in the browser.这是浏览器中的完整细节和兼容性。

toFixed function is used for restricting float numbers to 2 decimal places in javascript toFixed函数用于将浮点数限制为javascript中的2位小数

two_decimal_num = parseFloat(3.14159.toFixed(2));
console.log(two_decimal_num)

There's also the Intl API to format decimals according to your locale value.还有Intl API 可根据您的区域设置值格式化小数。 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.请注意,这将四舍五入到最多 3 个小数位,就像上面在默认情况下建议的round()函数一样。 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)

with toFixed you can set length of decimal points like this:使用toFixed您可以像这样设置小数点的长度:

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.但是toFixed返回一个字符串,如果number根本没有小数点,它会添加多余的零。

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

I used this way if you need 2 digits and not string type.如果您需要 2 位数字而不是字符串类型,我会使用这种方式。

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

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM