arma
arma

Reputation: 4124

How to remove decimal sign from number but preserve all digits?

How to convert this 20,00 into 2000 in javascript ? Basically how to remove decimal sign but keep all digits?

Upvotes: 1

Views: 4041

Answers (6)

Felix Kling
Felix Kling

Reputation: 816334

If you only have on comma in your string, you don't event need regex:

"20,00".replace(',', '');
// gives 2000

Upvotes: 0

Piskvor left the building
Piskvor left the building

Reputation: 92752

Everybody stand back, I know regular expressions!

var originalstring = '20,00';
var newstring = originalstring.replace(/,/g, '');

In other words, replace() all occurences of , with an empty string. You could even use a character class to remove anything except digits, if that's your intention:

var originalstring = '20,00';
var newstring = originalstring.replace(/[^0-9]/g, '');

That may be useful as the decimal delimiter is locale-specific (which e.g. means that in English (en_US), "two and a half" is "2.5", whereas in Czech (cs_CZ) it's "2,5"). Although JS always uses the decimal point for numbers, user-entered data will depend on the locale (e.g. the key next to 0 on numpad emits a , in some layouts), which can lead to confusion if your script expects a decimal comma and gets a decimal point instead.

Upvotes: 10

user113716
user113716

Reputation: 322462

Here's a non-regex way.

var result = "20,00".split(',').join('');

Upvotes: 1

Lucas Moeskops
Lucas Moeskops

Reputation: 5443

I assume your number is a string. Then you could do parseInt('20.00'.replace(/\./, '')) or in your case, if you use comma as separator, parseInt('20.00'.replace(/,/, '')).

Upvotes: 0

Stephen
Stephen

Reputation: 18964

Regular Expressions are your friend:

"20,00".replace(/[^\D]/g, '');

This will remove anything that's not a digit.

Upvotes: 2

Adam
Adam

Reputation: 44929

Use replace

"20,00".replace(/,/g,"")

Upvotes: 3

Related Questions