1

From a datasource I'm getting many numbers that need formatting before presenting in a browser.

Some of the numbers appear with trailing zeros, and some of the numbers appear with a trailing decimal point with nothing afterwards.

Here are examples of what I've been trying to achieve with Javascript's RegEx implementation:

130.0000     = 130
132.0050     = 132.005
16.9000      = 16.9
140000000.00 = 140000000
132.         = 132
89.0         = 89
90.0         = 90
9000.00      = 9000
99.0         = 99
99.00500     = 99.005
70           = 70 //fail, as it matches the zeros at the end if there's no decimal point
700          = 700 //fail, as it matches the zeros at the end if there's no decimal point

The following RegEx matches everything correctly except the last two tests where any zeros before the decimal point are also matched:

[\.0]0*$

Any help with what's now giving me a headache would be greatly appreciated.

Many thanks in advance...

user2190690
  • 1,744
  • 4
  • 24
  • 31
  • 1
    `[\.0]` means *either a `.` or a `0`*. You probably meant `(\.0)`. – Pointy Jul 11 '16 at 15:57
  • I think, if you go the regex route, you'd have to use two seperate regexes. `\.0*$` to match trailing zeros, including the decimal point, and something like `\.\d*?(0*)$` to capture trailing zeros (in a capture group this time) but only following a decimal point. Combining the two seems quite complicated, and you might be better off with a different approach. – SpoonMeiser Jul 11 '16 at 16:13
  • 1
    @SpoonMeiser: Not that complicated: `\.0*(?!\d)|(\.\d*?)0+\b` and replace with `$1`. But the accepted answer is still better. – Alan Moore Jul 11 '16 at 17:28
  • @AlanMoore, very impressive. Many thanks for your answer. Whilst I agree that the accepted answer is the best solution I was scratching my head trying to work out the RegEx. – user2190690 Jul 11 '16 at 17:33

1 Answers1

4

The most robust function that will take all of your inputs and trim them is parseFloat:

const values = [
  '130.0000',
  '132.0050',
  '16.9000',
  '140000000.00',
  '132.',
  '89.0',
  '90.0',
  '9000.00',
  '99.0',
  '99.00500',
  '70',
  '700'
];

values.map(parseFloat).forEach(it => console.log(it));

You can then use any of the Number methods to get a specific precision, round, reformat, etc.

While regular expressions can do many unholy things, sometimes there's a function that just works.

Community
  • 1
  • 1
ssube
  • 47,010
  • 7
  • 103
  • 140