格式号总是显示2位小数

时间:2023-01-14 16:55:17

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 1 as 1, rather than 1.00.

但它显示的是1而不是1。00。

22 个解决方案

#1


739  

This works fine in FF4:

这在FF4中工作得很好:

parseFloat(Math.round(num3 * 100) / 100).toFixed(2);

Live Demo

现场演示

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

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

var num3 = "1.345";
document.getElementById('num3').innerHTML = parseFloat(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 round to 2 decimal places, so the input 1.346 will return 1.35.

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

#2


191  

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

#3


59  

This answer will fail if value = 1.005.

如果值= 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').toFixed(2); // 1.01

Credit: Rounding Decimals in JavaScript

优点:在JavaScript中舍入小数

#4


14  

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

#5


12  

Simplest answer:

简单的回答是:

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

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

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

#6


7  

var number = 123456.789;


console.log(new Intl.NumberFormat('en-IN', { maximumFractionDigits: 2 }).format(number));

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

#7


7  

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

如果您已经使用了jQuery,那么可以使用jQuery数字格式插件。

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数字格式。

#8


7  

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, this article, and MDN's Math.round reference.

感谢Razu,这篇文章和MDN的数学。圆的参考。

#9


7  

A much more generic solution for rounding to N places

一个更通用的四舍五入的解决方案

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

#10


6  

Is this what you mean?

你是这个意思吗?

function showAsFloat(num, n){
      return !isNaN(+num) ? (+num).toFixed(n || 2) : num;
}

document.querySelector('#result').textContent = 
    [
     'command                      | result',
     '-----------------------------------------------',
     'showAsFloat(1);              | ' + showAsFloat(1),
     'showAsFloat(1.314);          | ' + showAsFloat(1.314),
     'showAsFloat(\'notanumber\')    | ' + showAsFloat('notanumber'),
     'showAsFloat(\'23.44567\', 3)   | ' + showAsFloat('23.44567', 3),
     'showAsFloat(2456198, 5)      | ' + showAsFloat('2456198', 5),
     'showAsFloat(0);              | ' + showAsFloat(0)
    ].join('\n');
<pre id="result"></pre>

#11


4  

Convert a number into a string, keeping only two decimals:

将一个数字转换成一个字符串,只保留两个小数:

var num = 5.56789;
var n = num.toFixed(2);

The result of n will be:

n的结果是:

5.57

#12


3  

Are you looking for floor?

你在找地板吗?

var num = 1.42482;
var num2 = 1;
var fnum = Math.floor(num).toFixed(2);
var fnum2 = Math.floor(num2).toFixed(2);
alert(fnum + " and " + fnum2); //both values will be 1.00

#13


3  

Here's also a generic function that can format to any number of decimal places:

这里还有一个通用函数,可以格式化为任意数量的小数:

function numberFormat(val, decimalPlaces) {

    var multiplier = Math.pow(10, decimalPlaces);
    return (Math.round(val * multiplier) / multiplier).toFixed(decimalPlaces);
}

#14


3  

Where specific formatting is required, you should write your own routine or use a library function that does what you need. The basic ECMAScript functionality is usually insufficient for displaying formatted numbers.

在需要特定格式的情况下,您应该编写自己的例程,或者使用可以满足您需要的库函数。基本的ECMAScript功能通常不足以显示格式化的数字。

A thorough explanation of rounding and formatting is here: http://www.merlyn.demon.co.uk/js-round.htm#RiJ

完整的四舍五入和格式解释如下:http://www.merlyn.demon.co.uk/js-round.htm#RiJ

As a general rule, rounding and formatting should only be peformed as a last step before output. Doing so earlier may introduce unexpectedly large errors and destroy the formatting.

一般来说,舍入和格式化应该作为输出前的最后一步。早些时候这样做可能会带来意想不到的大错误并破坏格式。

#15


2  

function currencyFormat (num) {
    return "$" + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
}

console.info(currencyFormat(2665));   // $2,665.00
console.info(currencyFormat(102665)); // $102,665.00

#16


1  

You are not giving us the whole picture.

你没有告诉我们全部情况。

javascript:alert(parseFloat(1).toFixed(2)) shows 1.00 in my browsers when I paste it int0 the location bar. However if you do something to it afterwards, it will revert.

javascript:alert(parseFloat(1). tofixed(2))在我的浏览器中显示1.00,当我将它粘贴到地址栏时。但是,如果您在之后对它做了什么,它将恢复原样。

var num = 2
document.getElementById('spanId').innerHTML=(parseFloat(num).toFixed(2)-1)


shows 1 and not 1.00

#17


1  

var quantity = 12;

var import1 = 12.55;

var total = quantity * import1;

var answer = parseFloat(total).toFixed(2);

document.write(answer);

#18


1  

function number_format(string,decimals=2,decimal=',',thousands='.',pre='R$ ',pos=' Reais'){
  var numbers = string.toString().match(/\d+/g).join([]);
  numbers = numbers.padStart(decimals+1, "0");
  var splitNumbers = numbers.split("").reverse();
  var mask = '';
  splitNumbers.forEach(function(d,i){
    if (i == decimals) { mask = decimal + mask; }
    if (i>(decimals+1) && ((i-2)%(decimals+1))==0) { mask = thousands + mask; }
    mask = d + mask;
  });
  return pre + mask + pos;
}
var element = document.getElementById("format");
var money= number_format("10987654321",2,',','.');
element.innerHTML = money;
#format{
display:inline-block;
padding:10px;
border:1px solid #ddd;
background:#f5f5f5;
}
<div id='format'>Test 123456789</div>

#19


0  

I do like:

我喜欢:

var num = 12.749;
parseFloat((Math.round(num * 100) / 100).toFixed(2)); // 123.75

Round the number with 2 decimal points, then make sure to parse it with parseFloat() to return Number, not String unless you don't care if it is String or Number.

用2个小数点环绕数字,然后确保用parseFloat()解析它以返回数字,而不是字符串,除非您不关心它是字符串还是数字。

#20


0  

Extend Math object with precision method

用精确的方法扩展数学对象

Object.defineProperty(Math, 'precision',{
   value: function (value,precision,type){
             var v = parseFloat(value),
                 p = Math.max(precision,0)||0,
                 t = type||'round';
              return (Math[t](v*Math.pow(10,p))/Math.pow(10,p)).toFixed(p);
          }
    });

console.log(
    Math.precision(3.1,3), // round 3 digits 
    Math.precision(0.12345,2,'ceil'), // ceil 2 digits
    Math.precision(1.1) // integer part
)

#21


-1  

(num + "").replace(/^([0-9]*)(\.[0-9]{1,2})?.*$/,"$1$2")

#22


-1  

This is how I solve my problem:

这就是我解决问题的方法:

parseFloat(parseFloat(floatString).toFixed(2));

parseFloat(parseFloat(floatString).toFixed(2));

#1


739  

This works fine in FF4:

这在FF4中工作得很好:

parseFloat(Math.round(num3 * 100) / 100).toFixed(2);

Live Demo

现场演示

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

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

var num3 = "1.345";
document.getElementById('num3').innerHTML = parseFloat(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 round to 2 decimal places, so the input 1.346 will return 1.35.

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

#2


191  

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

#3


59  

This answer will fail if value = 1.005.

如果值= 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').toFixed(2); // 1.01

Credit: Rounding Decimals in JavaScript

优点:在JavaScript中舍入小数

#4


14  

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

#5


12  

Simplest answer:

简单的回答是:

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

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

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

#6


7  

var number = 123456.789;


console.log(new Intl.NumberFormat('en-IN', { maximumFractionDigits: 2 }).format(number));

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

#7


7  

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

如果您已经使用了jQuery,那么可以使用jQuery数字格式插件。

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数字格式。

#8


7  

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, this article, and MDN's Math.round reference.

感谢Razu,这篇文章和MDN的数学。圆的参考。

#9


7  

A much more generic solution for rounding to N places

一个更通用的四舍五入的解决方案

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

#10


6  

Is this what you mean?

你是这个意思吗?

function showAsFloat(num, n){
      return !isNaN(+num) ? (+num).toFixed(n || 2) : num;
}

document.querySelector('#result').textContent = 
    [
     'command                      | result',
     '-----------------------------------------------',
     'showAsFloat(1);              | ' + showAsFloat(1),
     'showAsFloat(1.314);          | ' + showAsFloat(1.314),
     'showAsFloat(\'notanumber\')    | ' + showAsFloat('notanumber'),
     'showAsFloat(\'23.44567\', 3)   | ' + showAsFloat('23.44567', 3),
     'showAsFloat(2456198, 5)      | ' + showAsFloat('2456198', 5),
     'showAsFloat(0);              | ' + showAsFloat(0)
    ].join('\n');
<pre id="result"></pre>

#11


4  

Convert a number into a string, keeping only two decimals:

将一个数字转换成一个字符串,只保留两个小数:

var num = 5.56789;
var n = num.toFixed(2);

The result of n will be:

n的结果是:

5.57

#12


3  

Are you looking for floor?

你在找地板吗?

var num = 1.42482;
var num2 = 1;
var fnum = Math.floor(num).toFixed(2);
var fnum2 = Math.floor(num2).toFixed(2);
alert(fnum + " and " + fnum2); //both values will be 1.00

#13


3  

Here's also a generic function that can format to any number of decimal places:

这里还有一个通用函数,可以格式化为任意数量的小数:

function numberFormat(val, decimalPlaces) {

    var multiplier = Math.pow(10, decimalPlaces);
    return (Math.round(val * multiplier) / multiplier).toFixed(decimalPlaces);
}

#14


3  

Where specific formatting is required, you should write your own routine or use a library function that does what you need. The basic ECMAScript functionality is usually insufficient for displaying formatted numbers.

在需要特定格式的情况下,您应该编写自己的例程,或者使用可以满足您需要的库函数。基本的ECMAScript功能通常不足以显示格式化的数字。

A thorough explanation of rounding and formatting is here: http://www.merlyn.demon.co.uk/js-round.htm#RiJ

完整的四舍五入和格式解释如下:http://www.merlyn.demon.co.uk/js-round.htm#RiJ

As a general rule, rounding and formatting should only be peformed as a last step before output. Doing so earlier may introduce unexpectedly large errors and destroy the formatting.

一般来说,舍入和格式化应该作为输出前的最后一步。早些时候这样做可能会带来意想不到的大错误并破坏格式。

#15


2  

function currencyFormat (num) {
    return "$" + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
}

console.info(currencyFormat(2665));   // $2,665.00
console.info(currencyFormat(102665)); // $102,665.00

#16


1  

You are not giving us the whole picture.

你没有告诉我们全部情况。

javascript:alert(parseFloat(1).toFixed(2)) shows 1.00 in my browsers when I paste it int0 the location bar. However if you do something to it afterwards, it will revert.

javascript:alert(parseFloat(1). tofixed(2))在我的浏览器中显示1.00,当我将它粘贴到地址栏时。但是,如果您在之后对它做了什么,它将恢复原样。

var num = 2
document.getElementById('spanId').innerHTML=(parseFloat(num).toFixed(2)-1)


shows 1 and not 1.00

#17


1  

var quantity = 12;

var import1 = 12.55;

var total = quantity * import1;

var answer = parseFloat(total).toFixed(2);

document.write(answer);

#18


1  

function number_format(string,decimals=2,decimal=',',thousands='.',pre='R$ ',pos=' Reais'){
  var numbers = string.toString().match(/\d+/g).join([]);
  numbers = numbers.padStart(decimals+1, "0");
  var splitNumbers = numbers.split("").reverse();
  var mask = '';
  splitNumbers.forEach(function(d,i){
    if (i == decimals) { mask = decimal + mask; }
    if (i>(decimals+1) && ((i-2)%(decimals+1))==0) { mask = thousands + mask; }
    mask = d + mask;
  });
  return pre + mask + pos;
}
var element = document.getElementById("format");
var money= number_format("10987654321",2,',','.');
element.innerHTML = money;
#format{
display:inline-block;
padding:10px;
border:1px solid #ddd;
background:#f5f5f5;
}
<div id='format'>Test 123456789</div>

#19


0  

I do like:

我喜欢:

var num = 12.749;
parseFloat((Math.round(num * 100) / 100).toFixed(2)); // 123.75

Round the number with 2 decimal points, then make sure to parse it with parseFloat() to return Number, not String unless you don't care if it is String or Number.

用2个小数点环绕数字,然后确保用parseFloat()解析它以返回数字,而不是字符串,除非您不关心它是字符串还是数字。

#20


0  

Extend Math object with precision method

用精确的方法扩展数学对象

Object.defineProperty(Math, 'precision',{
   value: function (value,precision,type){
             var v = parseFloat(value),
                 p = Math.max(precision,0)||0,
                 t = type||'round';
              return (Math[t](v*Math.pow(10,p))/Math.pow(10,p)).toFixed(p);
          }
    });

console.log(
    Math.precision(3.1,3), // round 3 digits 
    Math.precision(0.12345,2,'ceil'), // ceil 2 digits
    Math.precision(1.1) // integer part
)

#21


-1  

(num + "").replace(/^([0-9]*)(\.[0-9]{1,2})?.*$/,"$1$2")

#22


-1  

This is how I solve my problem:

这就是我解决问题的方法:

parseFloat(parseFloat(floatString).toFixed(2));

parseFloat(parseFloat(floatString).toFixed(2));