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