-1

I have the below code in TypeScript that converts string to 2 decimal places:

new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
    .format(Number(value));

It works fine for the following input:

1 --> 1,00 12 --> 12,00

But I also want it to convert 12,5 to 12,50.

When I input 12,5 - because of the existing comma, it returns NaN. One possible solution is to replace the commas with a dot as per below:

const formattedValue: string = value.replace(',', '.');

But I do not want this approach. I was wondering if there is a specific method, to convert string to 2 decimal places using commas?

Also important, it should keep the original 2 decimal places and no rounding.

avdeveloper
  • 449
  • 6
  • 30
  • `value = value.replace(',', '.');`, then run your `Intl.NumberFormat` code... – Heretic Monkey Jul 19 '22 at 13:20
  • Does this answer your question? [How can I parse a string with a comma thousand separator to a number?](https://stackoverflow.com/questions/11665884/how-can-i-parse-a-string-with-a-comma-thousand-separator-to-a-number) – Heretic Monkey Jul 19 '22 at 13:21

1 Answers1

0

You need to apply the replacement not after you formatted it, but before you parse value to a number.

const format = (value) => new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
    .format(Number(value.replace(",",".")));


console.log(format("1"))
console.log(format("12,5"))
    
Jamiec
  • 133,658
  • 13
  • 134
  • 193