0

How to convert number to string like this:

input: 120000.564 output: "120 000.56"

input: 12000.564 output: "12 000.56"

Marty
  • 534
  • 8
  • 24

4 Answers4

2

There are many different ways of printing an integer with a space as a thousands separators in JavaScript. Here is one of the simplest ways is to use String.prototype.replace() function with the following arguments: regular expression: (?=(\d{3})+(?!\d)) and replacement value: '$1 '

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

console.log(formatNumber(120000.564));
1

For formatting numbers, there is 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)
Artem Bozhko
  • 1,744
  • 11
  • 12
0

Use .toString() Example :

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

Hi this is vague and broad question expect same kind of answer too you need to do 2 step

  1. make your number upto 2 digit as currency (Auxiliary step if you needed).

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

  2. just giving you another function to use it [credits][1] refer for some new requirements.

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)
  }
};
ThinkTank
  • 1,737
  • 5
  • 22
  • 36