0

I want to extract a float number from a string with 2 or 3 decimal places after coma without rounding (not toFixed) in jquery

Examples (2 decimals)

'43,999999' => 43.99
'324324243,669' => 324324243.66
'0,229' => 0.22
'0,2' => 0.2 or 0.20
'0.9' => 0.9 or 0.90

Examples (3 decimals)

'43,999999' => 43.999
'324324243,669' => 324324243.669
'0,229' => 0.229
'0,2' => 0.2 or 0.200
'0.9' => 0.9 or 0.900

I've tried [-+]?([0-9]*,[0-9]+|[0-9]+) but doesnt work

Any regex expert? Thanks in advance

David
  • 45
  • 1
  • 6

1 Answers1

1

Upto two decimal places.

^(\d+)[.,](\d{1,2})\d*$

Replace the matched chars with $1.$2. For three decimal places, you need to use

^(\d+)[.,](\d{1,3})\d*$

DEMO

> '43,999999'.replace(/^(\d+)[.,](\d{1,2})\d*$/g, '$1.$2')
'43.99'
> '43,999999'.replace(/[.,](\d{1,2})\d*$/g, '.$1')
'43.99'
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274