I would like to format my numbers to always display 2 decimal places, rounding where applicable.
Examples:
number display
------ -------
1
On input you have string (because you use parse) so we can get result by using only string manipulations and integer number calculations
let toFix2 = (n) => n.replace(/(-?)(\d+)\.(\d\d)(\d+)/, (_,s,i,d,r)=> {
let k= (+r[0]>=5)+ +d - (r==5 && s=='-');
return s + (+i+(k>99)) + "." + ((k>99)?"00":(k>9?k:"0"+k));
})
// TESTs
console.log(toFix2("1"));
console.log(toFix2("1.341"));
console.log(toFix2("1.345"));
console.log(toFix2("1.005"));
Explanation
s
is sign, i
is integer part, d
are first two digits after dot, r
are other digits (we use r[0]
value to calc rounding)k
contains information about last two digits (represented as integer number)r[0]
is >=5
then we add 1
to d
- but in case when we have minus number (s=='-'
) and r
is exact equal to 5 then in this case we substract 1 (for compatibility reasons - in same way Math.round
works for minus numbers e.g Math.round(-1.5)==-1
)k
are greater than 99 then we add one to integer part i