Search code examples
javascriptstringnumber-formatting

How to remove numbers after a comma?


I have strings like this: 300.123,25 and after the comma I want to have always one digit.

Expected result: 300.123,2

Another issue would be to auto concatenate ,0 if the string does not have a comma

300.123  ->  300.123,0  

With the value from the input:

value = value.toString().replace(/[^0-9\,]/g, "")
value = value.replace(/\B(?=(\d{3})+(?!\d))/g, ".")

I removed letters and other symbols. I've tried to check if I a have digits after comma with this: '(,\d)\d*$'. But it doesn't work.


Solution

  • const value = `300.123,25`;
    const parts = value.split(",");
    const result = `${parts[0]},${parts[1] ? (parts[1][0] || "0") : "0"}`;
    console.log(result);