在JavaScript中使用逗号十进制分隔符解析数字 [英] Parsing numbers with a comma decimal separator in JavaScript

查看:69
本文介绍了在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.

我试图这样做:

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);
}

如果我的陈述不够清楚,则数字看起来像这样的9.000,28而不是通常的9,000.28.

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

推荐答案

您需要先在千位分隔符中替换(删除)点,然后注意小数点:

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);
}

这篇关于在JavaScript中使用逗号十进制分隔符解析数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆