如何将数字转换为带浮点数的字符串?

时间:2020-05-19 09:52:11

标签: javascript

如何将数字转换为这样的字符串:

输入:120000.564 输出:“ 120 000.56”

输入:12000.564 输出:“ 12 000.56”

4 个答案:

答案 0 :(得分:2)

在JavaScript中,有很多不同的方式来打印一个整数,该整数的空间为千位分隔符。 这是最简单的方法之一,是将String.prototype.replace()函数与以下参数一起使用:regular expression: (?=(\d{3})+(?!\d))replacement value: '$1 '

function formatNumber(num) {
  return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1 ')
}

console.log(formatNumber(120000.564));

答案 1 :(得分:1)

要设置数字格式,请使用Intl.NumberFormat

var n = 120000.564;
var formatter = new Intl.NumberFormat('fr', { //space separator used in french locale
  style: 'decimal',
  maximumFractionDigits: 2
});
formatter.format(n)

答案 2 :(得分:0)

使用.toString() 示例:

let input = 1.242724;
let output = input.toString();
console.log(output);

答案 3 :(得分:0)

嗨,这是一个模糊而广泛的问题 也期待同样的答案 你需要做两步

  1. 使您的电话号码最多2位数字作为货币(如果需要,可以使用辅助步骤)。

    parseFloat(120000.564,1).toFixed(2);

  2. 只是给您另一个使用它的功能[学分] [1]请参考一些新要求。

function formatMoney(amount, decimalCount = 2, decimal = ".", thousands = " ") {
  try {
    decimalCount = Math.abs(decimalCount);
    decimalCount = isNaN(decimalCount) ? 2 : decimalCount;

    const negativeSign = amount < 0 ? "-" : "";

    let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString();
    let j = (i.length > 3) ? i.length % 3 : 0;

    return negativeSign + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "");
  } catch (e) {
    console.log(e)
  }
};