Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing numbers with a comma decimal separator in JavaScript

I used this function to check if a value is a number:

function isNumber(n) {     return !isNaN(parseFloat(n)) && isFinite(n); } 

My program need to work with German values. We use a comma as the decimal separator instead of a dot, so this function doesn't work.

I tried to do this:

n.replace(",",".") 

But it also doesn't seem to work. The exact function I tried to use is:

function isNumber(n) {     n=n.replace(",",".");     return !isNaN(parseFloat(n)) && isFinite(n); } 

The number looks like this 9.000,28 instead of the usual 9,000.28 if my statement wasn't clear enough.

like image 382
Chaos Avatar asked Aug 23 '13 14:08

Chaos


People also ask

How can I parse a string with a comma thousand separator to a number?

We can parse a number string with commas thousand separators into a number by removing the commas, and then use the + operator to do the conversion. We call replace with /,/g to match all commas and replace them all with empty strings.

How do you change the decimal separator in numbers?

Click File > Options. On the Advanced tab, under Editing options, clear the Use system separators check box. Type new separators in the Decimal separator and Thousands separator boxes. Tip: When you want to use the system separators again, select the Use system separators check box.


2 Answers

You need to replace (remove) the dots first in the thousands separator, then take care of the decimal:

function isNumber(n) {     'use strict';     n = n.replace(/\./g, '').replace(',', '.');     return !isNaN(parseFloat(n)) && isFinite(n); } 
like image 72
rink.attendant.6 Avatar answered Sep 22 '22 04:09

rink.attendant.6


var number = parseFloat(obj.value.replace(",","")); 

You'll probably also want this to go the other way...

obj.value = number.toLocaleString('en-US', {minimumFractionDigits: 2}); 
like image 33
Anthony Avatar answered Sep 22 '22 04:09

Anthony