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

查看:36
本文介绍了在 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天全站免登陆