0

I would like to format my decimal numbers to display 2 decimal places but .00 will always hide.

example

value      expect     return     
------     -------    ------
1.00       1           1.00
1          1           1.00
1.6        1.60        1.60
1.451      1.45        1.45



My Code

Vue.filter("currency", value => {
    return parseFloat(value).toFixed(2);
});

5 Answers5

3

Remove .00 from the end if it exists:

 return parseFloat(value).toFixed(2).replace(/\.00$/, '')
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

You can simply put the toFixed INTO the parseFloat like this:

Vue.filter("currency", value => {
    return parseFloat(value.toFixed(2))
});

toFixed will round/pad the number to a specific length, but also convert it to a string. Converting that back to a numeric type will not only make the number safer to use arithmetically, but also automatically drop any trailing 0's.

Reference: https://newbedev.com/remove-insignificant-trailing-zeros-from-a-number

Update

This solution doesn't consider the case: 1.6 -> 1.60 (check jsfiddle in the comment)

tho-masn
  • 1,126
  • 1
  • 7
  • 13
  • 1
    This wont work, this will only round the number to maximum of 2 decimal places. Wont work with inputs with one decimal place. Works only with no or more than 2 decimal places Fiddle https://jsfiddle.net/ku2ey76p/ – Nitheesh Sep 09 '21 at 06:58
  • Good point - thanks for clarification. Didn't consider that case. – tho-masn Sep 09 '21 at 07:08
  • Please fix that issue, so that I can revert the downvote. – Nitheesh Sep 09 '21 at 07:25
0

Just check whether the number is wholenumber by checking the reminder on division with 1

Vue.filter("currency", value => {
    return parseFloat(value) % 1 === 0 ? parseFloat(value).toString() : parseFloat(value).toFixed(2);
});
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
0

Check if the number converted to Integer has same value. return accordingly. change the parseint according to your requirements

Vue.filter("currency", (value )=>{
    if(value === parseInt(value )){return value}
    else {return parseFloat(value ).toFixed(2)}
}
5warag
  • 46
  • 2
0

regex version:

Intl.NumberFormat('en', { style:'currency', currency:'usd' }).format(num).replace(/\.?0*$/, '');
// $12.00  ->  $12
// $12.4   ->  $12.4
// $12.44  ->  $12.44
// $12.04  ->  $12.04
J. Doe
  • 77
  • 1
  • 6