I want to get string input for money value and I need integer (cents) to store it. But I need to present it back to the user on UI which mean that I need to get that value back from integer.
The problem is 455.000 (455 x 1000) but I get 455. So I made something terribly wrong in this calculation.
const toCent = amount => {
const str = amount.toString().replace(',', '.')
const [int] = str.split('.')
return Number(amount.toFixed(2).replace('.', '').padEnd(int.length === 1 ? 3 : 4, '0'))
}
console.log(toCent(parseFloat('45.99')));
console.log(toCent(parseFloat('455.000')));
console.log((Math.round((toCent(parseFloat('45.99')) / 100 + Number.EPSILON) * 100) / 100).toString());
console.log((Math.round((toCent(parseFloat('455.000')) / 100 + Number.EPSILON) * 100) / 100).toString());
The following snippet will work with input of the form D[sC] where D is dollars with optional thousands separators, s is the dollars-cents separator, and C is two-digit (zero-padded) cents.