我正在尝试开发一个采用数值的转换网站:
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 吗?请看我的另一个问题。 Regex - creating an input/textarea that correctly interprets numbers
最佳答案
关于javascript - 为什么我的 textarea (HTML) 值显示 12,000,000.11 但在 parseFloat 之后该值只有 12?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25436575/