Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

javascript - 检查数字是否有小数位/是整数(Check if a number has a decimal place/is a whole number)

I am looking for an easy way in JavaScript to check if a number has a decimal place in it (in order to determine if it is an integer).(我在JavaScript中寻找一种简单的方法来检查数字中是否有小数位(以确定它是否是整数)。)

For instance,(例如,) 23 -> OK 5 -> OK 3.5 -> not OK 34.345 -> not OK if(number is integer) {...}   ask by Hans translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using modulus will work:(使用模数将起作用:)

num % 1 != 0 // 23 % 1 = 0 // 23.5 % 1 = 0.5 Note that this is based on the numerical value of the number, regardless of format.(请注意,这是基于数的数值 ,不论格式。) It treats numerical strings containing whole numbers with a fixed decimal point the same as integers:(它处理包含整数且整数固定的小数点的数字字符串:) '10.0' % 1; // returns 0 10 % 1; // returns 0 '10.5' % 1; // returns 0.5 10.5 % 1; // returns 0.5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...