JavaScript - 如何将数字检测为十进制(包括1.0) [英] JavaScript - How To Detect Number As A Decimal (Including 1.0)

查看:75
本文介绍了JavaScript - 如何将数字检测为十进制(包括1.0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感觉我在这里遗漏了一些明显的东西。这已被问过很多次了 - 答案通常归结为:

It feels like I am missing something obvious here. This has been asked a number of times - and the answer usually boils down to:

var num = 4.5;
num % 1 === 0; // false - 4.5 is a decimal

但是,

var num = 1.0; // or 2.0, 3.0, ...
num % 1 // 0

不幸的是,这些都不起作用

Unfortunately, these doesn't work either

num.toString() // 1
typeof num // "number"

我正在编写一个JavaScript颜色解析库,我希望以不同的方式处理输入1.0或1.在我的情况下, 1.0 实际上意味着100%而 1 意味着1。

I am writing a JavaScript color parsing library, and I want to process input differently if it is given as 1.0 or 1. In my case, 1.0 really means 100% and 1 means 1.

否则,将解析 rgb 1 1 1 rgb 1 255 255 as rgb 255 255 255 (因为我现在正在采取任何< = 1来表示比率)。

Otherwise, both rgb 1 1 1 and rgb 1 255 255 will be parsed as rgb 255 255 255 (since I am right now taking anything <= 1 to mean a ratio).

推荐答案

这些数字实际上不是小数或整数。他们都是花车。 1 1.0 之间唯一真正的区别是用于创建相等值的浮点数的符号。



编辑:为了帮助说明,请考虑:

Those numbers aren't actually decimals or integers. They're all floats. The only real difference between 1 and 1.0 is the notation that was used to create floats of equal values.


to help illustrate, consider:

1 === 1.0; // true
parseInt('1') == parseInt('1.0'); // true
parseFloat('1') === parseFloat('1.0'); // true
parseInt('1') === parseFloat('1'); // true
// etc...

另外,为了证明它们确实是相同的基础数据类型:

Also, to demonstrate that they are really the same underlying data type:

typeof(1); // 'number'
typeof(1.0); // 'number'

另外,请注意'数字'在JavaScript中并不像它那样明确用其他语言,因为数字总是漂浮。



编辑2:还有一个补充,因为它是相关的。据我所知,JavaScript实际上具有真实和真实整数的唯一上下文并不是真正表示为浮点数,而是在进行按位运算时。但是,在这种情况下,解释器将所有浮点数转换为整数,执行操作,然后在返回控制之前将结果转换回浮点数。与这个问题并不完全相关,但它有助于很好地理解JS中的数字处理。

Also, note that 'number' isn't unambiguous in JavaScript like it would be in other languages, because numbers are always floats.


Edit 2: One more addition, since it's relevant. To the best of my knowledge, the only context in JavaScript in which you actually have "real and true" integers that aren't really represented as floats, is when you're doing bitwise operations. However, in this case, the interpreter converts all the floats to integers, performs the operation, and then converts the result back to a float before control is returned. Not totally pertinent to this question, but it helps to have a good understanding of Number handling in JS in general.

这篇关于JavaScript - 如何将数字检测为十进制(包括1.0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆