David
David

Reputation: 45

jquery extract float point number with 2 decimal places

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

Upvotes: 0

Views: 1314

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174696

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'

Upvotes: 1

Related Questions