Rya*_*oan 1 html javascript decimal comma parsefloat
我正在尝试开发一个带有数值的转换网站:
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
Run Code Online (Sandbox Code Playgroud)
通过textarea然后parseFloat数字以执行计算.这些是我得到的结果:
textarea input = 12,000.12
value after parseFloat = 12
Run Code Online (Sandbox Code Playgroud)
parseFloat无法识别数字的格式吗?我得到相同的结果:
textarea input: 12.000,12
value after parseFloat = 12
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?我似乎需要删除逗号,因为parseFloat不读取它们以及欧洲符号剥离小数并将逗号更改为小数以便parseFloat正确读取输入.关于如何解决这个问题的任何想法?我的猜测是我需要将字符串输入标识为欧洲或美国十进制表示法,然后执行所需的操作以为parseFloat准备字符串.我将如何实现这一目标?所有贡献都表示赞赏.使用HTML5和Javascript.这是我的第一个网站,所以请放轻松.
最好,RP
致所有贡献者......谢谢!到目前为止,所有的输入都是甜蜜的.我不认为我们将能够使用单个替换语句来正确地删除欧洲和美国符号,所以我认为我应该以某种方式使用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);
Run Code Online (Sandbox Code Playgroud)
这可能使用REGEX吗?请看我的另一个问题. 正则表达式 - 创建正确解释数字的输入/文本区域
一种方法是删除逗号,例如:
.replace(",", "")
Run Code Online (Sandbox Code Playgroud)
从那里你应该能够parseFloat
更新了小提琴:http://jsfiddle.net/aLv74xpu/2/
| 归档时间: |
|
| 查看次数: |
214 次 |
| 最近记录: |