【发布时间】:2014-08-21 21:52:57
【问题描述】:
我正在尝试开发一个采用数值的转换网站:
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然后parseFloat这个数字以便执行计算。 这些是我得到的结果:
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 - creating an input/textarea that correctly interprets numbers
【问题讨论】:
-
“1,234”是 4 位整数还是小数?
-
知道它总是2位小数吗?如果是这样,您可以分割字符串的末尾,剥离其余部分并从那里解析它
-
@recursive 或者。我希望能够以任何格式 1,234 1234 1.234(EUnotation) 输入数字并为 parseFloat 做好准备。
-
@Svedin 我希望他们能够输入最多 5 位小数。这是用于将度量长度从公制转换为英制标准
-
@RyanPaceSloan:但是如何你希望号码准备好?如果用户输入“1,234”,程序的正确输出是什么?您认为整数正确还是小数正确?还是允许程序选择它喜欢的那个?
标签: javascript html decimal comma parsefloat