Convert money value to cents

1.3k views Asked by At

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());

1

There are 1 answers

0
greg-tumolo On

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.

const toCent = amount => {
  const str = amount.replace(',', '.')
  return str.length < 3 || str[str.length - 3] == '.' ? Number(str.replace('.', '')) : Number(str.replace('.', ''))*100
}
console.log(toCent('45.99'));
console.log(toCent('455.000'));
console.log(toCent('45.99')/100);
console.log(toCent('455.000')/100);