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
139 views
in Technique[技术] by (71.8m points)

javascript - Input type number, decimal value

How to verify if an input type number contain maximum 3 decimal, without using regex

let x = 1.5555
let y = 1.55
x is false
y is true
question from:https://stackoverflow.com/questions/65933337/input-type-number-decimal-value

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

1 Answer

0 votes
by (71.8m points)

You can use a formula like:

(x * 1000) % 1 === 0

For numbers with 3 or fewer decimal places, the x*1000 will convert it into an integer. Eg:

1.55 -> 1550
1.555 -> 1555 

For numbers with more than 3 decimal places, doing x*1000 won't convert it to an int, it will only shift parts of the number over:

1.5555 -> 1555.5 // still a decimal

The % 1 check then gets the remainder of the above number if it was to be divided by 1. If the remainder is 0, then the number was converted to an integer, if it is more than 0, then x*1000 failed to convert the number to an int, meaning that it has more than 3 decimals:

const validate = x => (x * 1000) % 1 === 0;

console.log(validate(1.5555)); // false
console.log(validate(1.55)); // true
console.log(validate(1.555)); // true
console.log(validate(0.00000001)); // false

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

2.1m questions

2.1m answers

60 comments

57.0k users

...