带逗号和点Javascript的十进制数之间的区别 [英] Difference between decimal number with comma and dot Javascript
问题描述
如果值 >= 0,我应该验证输入表单.
I should validate an input form testing if value is >= 0.
我使用 jQuery 获取值并使用简单的 if 语句进行验证.像这样:
I get the value with jQuery and validate with a simple if statements. like this:
var value = $('#'+this.id).val();
console.log("value is " + value );
if(value >=0 ){
console.log("true");
}else{
console.log("false");
}
当用户插入带逗号或点的十进制数时会出现问题.如果用户插入 1.234
结果是 true
而如果插入 1,234
结果是 false
The problem raise when user inserts decimal number with comma or dot.
If user insert 1.234
the result is true
instead if inserts 1,234
the result is false
它们有什么区别?
我做了一个简单的小提琴来更好地解释情况.
I make a simple Fiddle for explain better the case.
http://jsfiddle.net/zzm8zno5/4/
我也验证了值的类型;我试图用 Number(value)
转换为数字,但没有任何变化
I also verified the type of value; I tried to cast as number with Number(value)
and nothing change
抱歉我的问题,也许是微不足道的,但我不明白为什么会这样
Sorry for my question, maybe is trivial but i don't understand why this happen
推荐答案
Javascript 无法将逗号识别为小数分隔符.你必须使用一个点,.
.
Javascript does not recognise the comma as the decimal separator. You have to use a dot, .
.
为此,您可以使用 replace()
更改值中的逗号.您还需要使用 parseFloat()
来比较值,否则您将数字 (0
) 与字符串 ('1.234'
) 进行比较>).试试这个:
To do this you can use replace()
to change the comma in the value. Also you need to use parseFloat()
to compare the value, otherwise you're comparing a number (0
) to a string ('1.234'
). Try this:
var value = parseFloat($(this).val().replace(',', '.'));
最后,请注意在 jQuery 对象中仅使用了 this
.由于您已经拥有对元素的引用,因此您无需构建另一个字符串选择器.如果您愿意,可以进一步缩短为 this.value
Finally, note the use of just this
in the jQuery object. Since you already have a reference to the element you don't need to build another string selector. If you prefer you could shorten that further to just this.value
更新
假设 1,234
的意思是 1234
而不是用作小数分隔符,那么您需要删除 ,
而无需替换:
Assuming that 1,234
is intended to mean 1234
and is not used as a decimal separator then you need to instead remove the ,
without replacement:
var value = parseFloat($(this).val().replace(',', ''));
这篇关于带逗号和点Javascript的十进制数之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!