简体   繁体   English

Javascript无限制地将浮点数转换为整数

[英]Javascript casts floating point numbers to integers without cause

I wrote a function that behaves differently depending on the numeric type of it's parameters. 我写了一个函数,它的行为有所不同,具体取决于它的参数的数字类型。 Integer or float. 整数或浮点数。

Using some code from this question How do I check that a number is float or integer? 使用此问题中的一些代码如何检查数字是浮点数还是整数? it was easy to detect if float or not but then I stumbled upon the case that javascript casts 1.0 to 1 without cause if you call a function using that number. 很容易检测浮动与否,但后来我偶然发现javascript在没有原因的情况下将1.0转换为1情况,如果您使用该数字调用函数。

Example: 例:

function dump(a, b) {
 console.log(a, typeof b, b);
}

dump('1', 1);
dump('1.0', 1.0);
dump('1.1', 1.1);

Output chrome, firefox, ie, opera and safari all gave the same result: 输出chrome,firefox,即opera和safari都给出了相同的结果:

1   number 1
1.0 number 1 "wrong"
1.1 number 1.1

I know that javascript only knows the type number but that forced cast seems to go way overboard. 我知道javascript只知道类型number但强制转换似乎过分了。 The only solution I came up with was to call the function using string values like '1.0' , detect the dot and use parseFloat or parseInt . 我想出的唯一解决方案是使用字符串值(如'1.0'调用函数,检测点并使用parseFloatparseInt

Any suggestion on that? 有什么建议吗?

You've acknowledged that JavaScript only has a single Number type. 您已经承认JavaScript只有一个Number类型。 As such, 1 is identical to 1.0 . 因此, 11.0相同。

If you need this for display purposes, then you should use toFixed . 如果您需要这个用于显示目的,那么您应该使用toFixed

1..toFixed(1); // "1.0"
number%1===0 

如果该条件为true ,则为整数,否则为浮点数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM