Javascript 格式化数字以始终显示 2 个小数位

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

Format number to always show 2 decimal places

javascriptfloating-pointnumber-formatting

提问by Varada

I would like to format my numbers to always display 2 decimal places, rounding where applicable.

我想格式化我的数字以始终显示 2 个小数位,并在适用的情况下四舍五入。

Examples:

例子:

number     display
------     -------
1          1.00
1.341      1.34
1.345      1.35

I have been using this:

我一直在使用这个:

parseFloat(num).toFixed(2);

But it's displaying 1as 1, rather than 1.00.

但它显示11, 而不是1.00

回答by drudge

(Math.round(num * 100) / 100).toFixed(2);

Live Demo

现场演示

var num1 = "1";
document.getElementById('num1').innerHTML = (Math.round(num1 * 100) / 100).toFixed(2);

var num2 = "1.341";
document.getElementById('num2').innerHTML = (Math.round(num2 * 100) / 100).toFixed(2);

var num3 = "1.345";
document.getElementById('num3').innerHTML = (Math.round(num3 * 100) / 100).toFixed(2);
span {
    border: 1px solid #000;
    margin: 5px;
    padding: 5px;
}
<span id="num1"></span>
<span id="num2"></span>
<span id="num3"></span>

Note that it will roundto 2 decimal places, so the input 1.346will return 1.35.

请注意,它将四舍五入到小数点后两位,因此输入1.346将返回1.35.

回答by Abel ANEIROS

Number(1).toFixed(2);         // 1.00
Number(1.341).toFixed(2);     // 1.34
Number(1.345).toFixed(2);     // 1.34 NOTE: See andy's comment below.
Number(1.3450001).toFixed(2); // 1.35

document.getElementById('line1').innerHTML = Number(1).toFixed(2);
document.getElementById('line2').innerHTML = Number(1.341).toFixed(2);
document.getElementById('line3').innerHTML = Number(1.345).toFixed(2);
document.getElementById('line4').innerHTML = Number(1.3450001).toFixed(2);
<span id="line1"></span>
<br/>
<span id="line2"></span>
<br/>
<span id="line3"></span>
<br/>
<span id="line4"></span>

回答by razu

This answerwill fail if value = 1.005.

这个答案将失败value = 1.005

As a better solution, the rounding problem can be avoided by using numbers represented in exponential notation:

作为更好的解决方案,可以通过使用以指数表示法表示的数字来避免舍入问题:

Number(Math.round(1.005+'e2')+'e-2'); // 1.01

Cleaner code as suggested by @Kon, and the original author:

@Kon 和原作者建议的更简洁的代码:

Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces)

You may add toFixed()at the end to retain the decimal point e.g: 1.00but note that it will return as string.

您可以toFixed()在末尾添加以保留小数点,例如:1.00但请注意,它将以字符串形式返回。

Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces).toFixed(decimalPlaces)

Credit: Rounding Decimals in JavaScript

信用:JavaScript 中的四舍五入小数

回答by Tiberiu Petcu

var num = new Number(14.12);
console.log(num.toPrecision(2));//outputs 14
console.log(num.toPrecision(3));//outputs 14.1
console.log(num.toPrecision(4));//outputs 14.12
console.log(num.toPrecision(5));//outputs 14.120

回答by Nate

For the most accurate rounding, create this function:

要获得最准确的舍入,请创建此函数:

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

and use it to round to 2 decimal places:

并使用它四舍五入到小数点后两位:

console.log("seeked to " + round(1.005, 2));
> 1.01

Thanks to Razu, thisarticle, and MDN's Math.round reference.

感谢Razu这篇文章和MDN 的 Math.round 参考

回答by holmis83

For modern browsers, use toLocaleString:

对于现代浏览器,请使用toLocaleString

var num = 1.345;
num.toLocaleString(undefined, { maximumFractionDigits: 2, minimumFractionDigits: 2 });

Specify a locale tag as first parameter to control the decimal separator. For a dot, use for example English U.S. locale:

指定语言环境标记作为第一个参数来控制小数点分隔符。对于点,例如使用英语美国语言环境:

num.toLocaleString("en-US", { maximumFractionDigits: 2, minimumFractionDigits: 2 });

which gives:

这使:

1.35

1.35

Most countries in Europe use a comma as decimal separator, so if you for example use Swedish/Sweden locale:

欧洲的大多数国家/地区使用逗号作为小数点分隔符,因此,例如,如果您使用瑞典/瑞典语言环境:

num.toLocaleString("sv-SE", { maximumFractionDigits: 2, minimumFractionDigits: 2 });

it will give:

它会给:

1,35

1,35

回答by macio.Jun

Simplest answer:

最简单的答案:

var num = 1.2353453;
num.toFixed(2); // 1.24

Example: http://jsfiddle.net/E2XU7/

示例:http: //jsfiddle.net/E2XU7/

回答by PirateApp

A much more generic solution for rounding to N places

四舍五入到 N 个位置的更通用的解决方案

function roundN(num,n){
  return parseFloat(Math.round(num * Math.pow(10, n)) /Math.pow(10,n)).toFixed(n);
}


console.log(roundN(1,2))
console.log(roundN(1.34,2))
console.log(roundN(1.35,2))
console.log(roundN(1.344,2))
console.log(roundN(1.345,2))
console.log(roundN(1.344,3))
console.log(roundN(1.345,3))
console.log(roundN(1.3444,3))
console.log(roundN(1.3455,3))

Output

1.00
1.34
1.35
1.34
1.35
1.344
1.345
1.344
1.346

回答by zloctb

回答by Sam Sehnert

If you're already using jQuery, you could look at using the jQuery Number Formatplugin.

如果你已经在使用 jQuery,你可以看看使用jQuery Number Format插件。

The plugin can return formatted numbers as a string, you can set decimal, and thousands separators, and you can choose the number of decimals to show.

该插件可以将格式化的数字作为字符串返回,您可以设置小数和千位分隔符,并且您可以选择要显示的小数位数。

$.number( 123, 2 ); // Returns '123.00'

You can also get jQuery Number Format from GitHub.

您还可以从 GitHub获取jQuery 数字格式