Javascript:比较两个浮点值 [英] Javascript: Comparing two float values
本文介绍了Javascript:比较两个浮点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个JavaScript函数:
Contrl.prototype.EvaluateStatement = function(acVal,cfVal){
var cv = parseFloat(cfVal).toFixed(2);
var av = parseFloat(acVal).toFixed(2);
if(av< cv)// do some thing
}
$ b b
当我比较浮动数字 av = 7.00
和 cv = 12.00
> 7.00< 12.00 是 false
!
>
解决方案
toFixed返回一个字符串,你正在比较两个结果字符串。词汇上,12中的1在7之前, 7。
我想你要比较一下:
(Math.round(parseFloat(acVal)* 100)/ 100)
/ p>
I have this JavaScript function:
Contrl.prototype.EvaluateStatement = function(acVal, cfVal) {
var cv = parseFloat(cfVal).toFixed(2);
var av = parseFloat(acVal).toFixed(2);
if( av < cv) // do some thing
}
When i compare float numbers av=7.00
and cv=12.00
the result of 7.00<12.00
is false
!
Any ideas why?
解决方案
toFixed returns a string, and you are comparing the two resulting strings. Lexically, the 1 in 12 comes before the 7 so 12 < 7.
I guess you want to compare something like:
(Math.round(parseFloat(acVal)*100)/100)
which rounds to two decimals
这篇关于Javascript:比较两个浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文