jQuery JavaScript 中的十进制比较失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18741177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:23:12  来源:igfitidea点击:

Decimal comparison failing in JavaScript

javascriptjquery

提问by User

I need to compare the following scenarios using decimal comparison in jquery.

我需要在 jquery 中使用十进制比较来比较以下场景。

var a=99999999999.99;
var b=9999999999999999999

if(parseFloat(a).toFixed(2) > parseFloat(b).toFixed(2))

This always returns true. How to fix the Issue?

这总是返回true。如何解决问题?

Some of the outputs from what I tried:

我尝试的一些输出:

parseFloat(9874563212).toFixed(2) > parseFloat(98745632).toFixed(2) true
parseFloat(98745632).toFixed(2) > parseFloat(987456321).toFixed(2) false
parseFloat(99999999999.99).toFixed(2) > parseFloat(9999999999999999999).toFixed(2) true
parseFloat(99999999999.99).toFixed(2) > parseFloat(999999999999).toFixed(2) false
parseFloat(99999999999.99).toFixed(2) > parseFloat(9999999999999).toFixed(2) false
parseFloat(99999999999.99).toFixed(2) > parseFloat(99999999999999).toFixed(2) false
parseFloat(99999999999.99).toFixed(2) > parseFloat(999999999999999).toFixed(2) false
parseFloat(99999999999.99).toFixed(2) > parseFloat(9999999999999999).toFixed(2) true
parseFloat(99999999999.99).toFixed(2) > parseFloat(1111111111111111).toFixed(2) true
parseFloat(99999999999.99).toFixed(2) > parseFloat(111111111111111).toFixed(2) true

回答by xanatos

You are comparing strings, not numbers (.toFixed()returns a string). Try:

您正在比较字符串,而不是数字(.toFixed()返回一个字符串)。尝试:

if (parseFloat(parseFloat(a).toFixed(2)) > parseFloat(parseFloat(b).toFixed(2)))

Or, if aand bare already numbers, as in your example

或者,如果ab已经是数字,如您的示例所示

if (parseFloat(a.toFixed(2)) > parseFloat(b.toFixed(2)))

Or better

或更好

if (Math.round(a * 100) > Math.round(b * 100))