javascript 将数字格式设置为两位小数

0kjbasz6  于 2023-09-29  发布在  Java
关注(0)|答案(4)|浏览(178)

给予我一个native(没有jQuery,Prototype等)JavaScript函数转换数字如下:

  1. input: 0.39, 2.5, 4.25, 5.5, 6.75, 7.75, 8.5
  2. output: 0.39, 2.50, 4.25, 5.50, 6.75, 7.75, 8.50

例如,在Ruby中,我会这样做:

  1. >> sprintf("%.2f", 2.5)
  2. => "2.50"

输出可以是数字或字符串。我不在乎,因为我只是用它来设置innerHTML
谢谢

ar5n3qh5

ar5n3qh51#

  1. input = 0.3;
  2. output = input.toFixed(2);
  3. // output: 0.30

一个较新的选项,它支持舍入:

  1. new Intl.NumberFormat('en-US', {
  2. minimumFractionDigits: 2,
  3. maximumFractionDigits: 2
  4. }).format(1.005)
  5. // Outputs: 1.01
guz6ccqo

guz6ccqo2#

可以在Number对象上使用toFixed()方法:

  1. var array = [0.39, 2.5, 4.25, 5.5, 6.75, 7.75, 8.5], new_array = [];
  2. for(var i = 0, j = array.length; i < j; i++) {
  3. if(typeof array[i] !== 'number') continue;
  4. new_array.push(array[i].toFixed(2));
  5. }
jrcvhitl

jrcvhitl3#

使用toFixed,2作为小数位数。

q3aa0525

q3aa05254#

或者,您可以将Intl.NumberFormat(){ style: 'percent'}一起使用

  1. var num = 25;
  2. var option = {
  3. style: 'percent'
  4. };
  5. var formatter = new Intl.NumberFormat("en-US", option);
  6. var percentFormat = formatter.format(num / 100);
  7. console.log(percentFormat);

相关问题