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);
});
Remove .00 from the end if it exists:
return parseFloat(value).toFixed(2).replace(/\.00$/, '')
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)
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);
});