1

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"));
}
cocool97
  • 1,201
  • 1
  • 10
  • 22
  • *"The problem I'm facing seems to be the use of parseFloat() which removes trailing zeros."* `parseFloat` doesn't remove trailing zeros. It converts from string to number. The standard number type has no concept of trailing zeros, that's a string-related concept, not a numeric one. – T.J. Crowder Dec 21 '19 at 17:14
  • Guess you may need something like [numeraljs](http://numeraljs.com/) as well as if you are using for webSite based on React, `react-number-format` is also a good option – keikai Dec 21 '19 at 17:16
  • @keikai This code runs in back-end sorry I haven't mentionned that... – cocool97 Dec 21 '19 at 17:18

1 Answers1

1

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)}
`);
Matt Oestreich
  • 8,219
  • 3
  • 16
  • 41
  • Thanks ! This solved my problem ! I just modified your code to add ```var x, x1, x2, rgx``` or it does not compile ! – cocool97 Dec 22 '19 at 10:17