Input type number, decimal value

Viewed 209

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
3 Answers

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

You can convert to string using the toString() method, then split at the point . with the .split() method this will result in an array. The first element in the array is a string containing the whole number part which is not interesting here for us. The second element at indice 1 in the resulting array is the decimal part as string.

Now you can check the length property of this string if it is equal or less then three which means it has three or less decimal numbers then we return true in the validation function when not we return false.

const x = 1.5555;
const y = 1.555;
const z = 1.55


function validate(num){
return num.toString().split(".")[1].length <= 3;
}

console.log(validate(x));
console.log(validate(y));
console.log(validate(z));

This may solve your problem

let x = 1.5555;
let y = 1.55;
int length = x.Substring(number.IndexOf(".")).Length;
bool result = length > 3 ? true: false;

Related