我正在尝试开发一个采用数值的转换网站:
1,200.12
or
1.200,12
or
1200.12
or
1200,12
and have them all interpreted as 1200.12 by parseFloat.
I would also like decimals to be able to be interpreted.
0.123
or
0,123
as 0.123
通过一个 textarea 然后解析浮点数以执行计算。这些是我得到的结果:
textarea input = 12,000.12
value after parseFloat = 12
parseFloat 不能识别数字的格式吗?我得到相同的结果:
textarea input: 12.000,12
value after parseFloat = 12
我该如何解决这个问题?看来我需要去掉逗号,因为 parseFloat 不会读取超出它们的内容,并且使用欧洲表示法去除小数并将逗号更改为小数,以便 parseFloat 正确读取输入。关于如何解决这个问题的任何想法?我的猜测是我需要将字符串输入识别为欧洲或美国十进制表示法,然后执行所需的操作来为 parseFloat 准备字符串。我将如何实现这一目标?感谢所有贡献。使用 HTML5 和 Javascript。这是我的第一个网站,所以请放轻松。
最佳,反相
致所有贡献者...谢谢!到目前为止,所有的输入都是甜蜜的。我不认为我们将能够使用单个替换语句来正确剥离欧洲和美国符号,所以我认为我应该以某种方式使用 REGEX 来确定符号,然后拆分为 if else 语句来执行单独的替换功能在每个单独的符号上。
var input, trim;
input = "1.234,56" //string from textarea on page
if(/REGEX that determines American Notation/.test(input){
trim = input.replace(/\,/,"");//removes commas and leaves decimal point);
}
else(/REGEX that determine European Notation/.test(input)/){ //would qualify input here
rep = input.replace(/\./,"");//removes all decimal points);
trim = rep.replace(/\,/,"."//changes the remaining comma to a decimal);
}
//now either notation should be in the appropriate form to parse
number = parseFloat(trim);
这可以使用 REGEX 吗?请看我的另一个问题。 正则表达式 - 创建正确解释数字的输入/文本区域