cocool97
cocool97

Reputation: 1251

Number formatting with toFixed() and toLocaleString()

I need to format numbers in a given way for my website.
Here is my problem :

I have 3 different cases :
1) First case : When my number is negative, I have to put parenthesis around it, and display its absolute value. The thing is, I have to keep 1 digit after the comma, even for "round" number like (218, 9744, etc...)
2) Second case : When my number equals to zero, I have to return 0.0 [this one is OK]
3) Third case : When my number is positive, I have to return it with one digit after the comma.

To make it easy, I have to use toLocaleString() function to format it in en-EN.
The problem I'm facing seems to be the use of parseFloat() which removes trailing zeros. Can someone help me ?

Here are a few examples of what I need :

218 -> 218.0
21800 -> 21,800.0
-21800 -> (21,800.0)

And my code :

if (number < 0) {
    return ('(' + Math.abs(floatNumber.toFixed(1)).toLocaleString("en-EN") + ')');
}
else if (number == 0.0) {
    return (floatNumber.toFixed(1))
}
else {
    return (parseFloat(floatNumber.toFixed(1)).toLocaleString("en-EN"));
}

Upvotes: 1

Views: 312

Answers (1)

Matt Oestreich
Matt Oestreich

Reputation: 8528

You should be able to do something like this:

function formatNumber(n) {
  return n < 0 
    ? `(${addCommas(Math.abs(n).toFixed(1))})` 
    : addCommas(n.toFixed(1));
}

function addCommas(n) {
  let x, x1, x2, rgx;
  n = String(n), x = n.split('.'), x1 = x[0], x2 = x.length > 1 ? '.' + x[1] : '', rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) x1 = x1.replace(rgx, '$1' + ',' + '$2');
  return x1 + x2;
}

console.log(`
Desired Results:
 218    => 218.0
 21800  => 21,800.0
 -21800 => (21,800.0)

Actual Results:
 218    => ${formatNumber(218)}
 21800  => ${formatNumber(21800)}
 -21800 => ${formatNumber(-21800)}
`);

Upvotes: 1

Related Questions