Parse the number into a string, split by a period and check whether the second item's length is 2:
function isPrecise(num){
return String(num).split(".")[1]?.length == 2;
}
console.log(isPrecise(1.23))
console.log(isPrecise(1.2))
console.log(isPrecise(1))
console.log(isPrecise("1.23")) //works if its a string too
You can also use a regex:
function isPrecise(num){
return /\d+\.\d{2}/gm.test(String(num));
}
console.log(isPrecise(1.23))
console.log(isPrecise(1.2))
console.log(isPrecise("1.23")) //works if its a string too
Answer from Spectric on Stack OverflowValidate a number to have 2 decimal points
javascript - How to check if a number has two decimal places and keep the trailing zero if necessary? - Stack Overflow
jquery - Simplest way of getting the number of decimals in a number in JavaScript - Stack Overflow
javascript - Check if a number has a decimal place/is a whole number - Stack Overflow
let a = 0; a += 0.8; a += 0.4; // a = 1.2000000000000002 let b = 0; b += 0.6; b += 0.6; // b = 1.2
How can I check the results are the same if a === b is false?
but toFixed turns it into a string, and if you use parseInt it gets rid of the trailing zero
You can have a number or you can have a representation of a number, but there is no third alternative.
If you want a representation of a number, what's wrong with a string? If you want a number, then there is no "trailing zero".
The number represented by "2.0" doesn't have a trailing zero because only representations can have trailing zeros. The number two can be represented with or without a trailing zero and it's the same number.
So: Do you want a number or a representation?
I think you must want a representation, because really only representation can have some specific number of decimal places. In that case, why isn't toString the right solution?
Assuming that x is the value you are dealing with
var temp = Math.round(x * 10) / 10; // This is the value as a number
document.write(temp.toFixed(1)); // writes the number in the desired format
In JavaScript, there is no distinction between the value 1.5 and the value 1.50 - as numbers, they are exactly the same. It is only when you convert them to a string, using something like toFixed(), that they become distinct.
Number.prototype.countDecimals = function () {
if(Math.floor(this.valueOf()) === this.valueOf()) return 0;
return this.toString().split(".")[1].length || 0;
}
When bound to the prototype, this allows you to get the decimal count (countDecimals();) directly from a number variable.
E.G.
var x = 23.453453453;
x.countDecimals(); // 9
It works by converting the number to a string, splitting at the . and returning the last part of the array, or 0 if the last part of the array is undefined (which will occur if there was no decimal point).
If you do not want to bind this to the prototype, you can just use this:
var countDecimals = function (value) {
if(Math.floor(value) === value) return 0;
return value.toString().split(".")[1].length || 0;
}
EDIT by Black:
I have fixed the method, to also make it work with smaller numbers like 0.000000001
Number.prototype.countDecimals = function () {
if (Math.floor(this.valueOf()) === this.valueOf()) return 0;
var str = this.toString();
if (str.indexOf(".") !== -1 && str.indexOf("-") !== -1) {
return str.split("-")[1] || 0;
} else if (str.indexOf(".") !== -1) {
return str.split(".")[1].length || 0;
}
return str.split("-")[1] || 0;
}
var x = 23.453453453;
console.log(x.countDecimals()); // 9
var x = 0.0000000001;
console.log(x.countDecimals()); // 10
var x = 0.000000000000270;
console.log(x.countDecimals()); // 13
var x = 101; // Integer number
console.log(x.countDecimals()); // 0
Adding to series0ne answer if you want to have the code not throw an error for an integer number and get a result of 0 when there are no decimals use this:
var countDecimals = function (value) {
if ((value % 1) != 0)
return value.toString().split(".")[1].length;
return 0;
};
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
Number.isInteger(23); // true
Number.isInteger(1.5); // false
Number.isInteger("x"); // false:
Number.isInteger() is part of the ES6 standard and not supported in IE11.
It returns false for NaN, Infinity and non-numeric arguments while x % 1 != 0 returns true.
I think my code is perfect ...
/**
* @param {string} s
* @return {boolean}
*/
var isNumber = function(s) {
return s.trim()!=="" && !isNaN(Number(s));
};
You can minimize this function in a lot of way, and you can also implement it with a custom regex for negative values or custom charts:
$('.number').on('input',function(){
var n=$(this).val().replace(/ /g,'').replace(/\D/g,'');
if (!$.isNumeric(n))
$(this).val(n.slice(0, -1))
else
$(this).val(n)
});