How do you check if a number has a decimal in javascript?

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). For instance,

23 -> OK
5 -> OK
3.5 -> not OK
34.345 -> not OK
if(number is integer) {...}

reformed

4,24510 gold badges59 silver badges83 bronze badges

asked Feb 20, 2010 at 22:48

How do you check if a number has a decimal in javascript?

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

How do you check if a number has a decimal in javascript?

answered Feb 20, 2010 at 22:50

Andy EAndy E

330k83 gold badges469 silver badges441 bronze badges

19

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.

answered Mar 15, 2017 at 2:16

How do you check if a number has a decimal in javascript?

le_mle_m

18.3k9 gold badges61 silver badges74 bronze badges

6

Or you could just use this to find out if it is NOT a decimal:

string.indexOf(".") == -1;

dYale

1,4531 gold badge16 silver badges19 bronze badges

answered Oct 24, 2011 at 15:31

IkeIke

7135 silver badges2 bronze badges

11

Simple, but effective!

Math.floor(number) === number;

answered Mar 2, 2015 at 17:26

dYaledYale

1,4531 gold badge16 silver badges19 bronze badges

3

The most common solution is to strip the integer portion of the number and compare it to zero like so:

function Test()
{
     var startVal = 123.456
     alert( (startVal - Math.floor(startVal)) != 0 )
}

answered Feb 20, 2010 at 23:25

ThomasThomas

62.9k11 gold badges93 silver badges139 bronze badges

11

//How about byte-ing it?

Number.prototype.isInt= function(){
 return this== this>> 0;
}

I always feel kind of bad for bit operators in javascript-

they hardly get any exercise.

answered Feb 21, 2010 at 1:15

kennebeckennebec

100k31 gold badges104 silver badges126 bronze badges

2

Number.isSafeInteger(value);

In JavaScript, isSafeInteger() is a Number method that is used to return a Boolean value indicating whether a value is a safe integer. This means that it is an integer value that can be exactly represented as an IEEE-754 double precision number without rounding.

answered Aug 10, 2021 at 12:58

aadityaaaditya

4697 silver badges19 bronze badges

1

Number.isInteger() is probably the most concise. It returns true if it is an integer, and false if it isn't.

How do you check if a number has a decimal in javascript?

answered Sep 3, 2018 at 19:45

How do you check if a number has a decimal in javascript?

4

number = 20.5

if (number == Math.floor(number)) {

alert("Integer")

} else {

alert("Decimal")

}

Pretty cool and works for things like XX.0 too! It works because Math.floor() chops off any decimal if it has one so if the floor is different from the original number we know it is a decimal! And no string conversions :)

answered Jun 6, 2017 at 0:41

0

var re=/^-?[0-9]+$/;
var num=10;
re.test(num);

answered Feb 21, 2010 at 0:09

ghostdog74ghostdog74

313k55 gold badges252 silver badges339 bronze badges

3

function isDecimal(n){
    if(n == "")
        return false;

    var strCheck = "0123456789";
    var i;

    for(i in n){
        if(strCheck.indexOf(n[i]) == -1)
            return false;
    }
    return true;
}

Sirko

70.5k19 gold badges143 silver badges175 bronze badges

answered Oct 26, 2012 at 19:30

2

parseInt(num) === num

when passed a number, parseInt() just returns the number as int:

parseInt(3.3) === 3.3 // false because 3 !== 3.3
parseInt(3) === 3     // true

answered Jan 21, 2015 at 19:05

MichaelMichael

21.4k33 gold badges128 silver badges182 bronze badges

1

convert number string to array, split by decimal point. Then, if the array has only one value, that means no decimal in string.

if(!number.split(".")[1]){
    //do stuff
}

This way you can also know what the integer and decimal actually are. a more advanced example would be.

number_to_array = string.split(".");
inte = number_to_array[0];
dece = number_to_array[1]; 

if(!dece){
    //do stuff
}

answered Jul 3, 2016 at 14:14

How do you check if a number has a decimal in javascript?

KareemKareem

4,65540 silver badges35 bronze badges

Use following if value is string (e.g. from ):

Math.floor(value).toString() !== value

I add .toString() to floor to make it work also for cases when value == "1." (ends with decimal separator or another string). Also Math.floor always returns some value so .toString() never fails.

answered Mar 26, 2020 at 10:01

How do you check if a number has a decimal in javascript?

michal.jakubeczymichal.jakubeczy

6,8861 gold badge52 silver badges57 bronze badges

Here's an excerpt from my guard library (inspired by Effective JavaScript by David Herman):

var guard = {

    guard: function(x) {
        if (!this.test(x)) {
            throw new TypeError("expected " + this);
        }
    }

    // ...
};

// ...

var number = Object.create(guard);
number.test = function(x) {
    return typeof x === "number" || x instanceof Number;
};
number.toString = function() {
    return "number";
};


var uint32 = Object.create(guard);
uint32.test = function(x) {
    return typeof x === "number" && x === (x >>> 0);
};
uint32.toString = function() {
    return "uint32";
};


var decimal = Object.create(guard);
decimal.test = function(x) {
    return number.test(x) && !uint32.test(x);
};
decimal.toString = function() {
    return "decimal";
};


uint32.guard(1234);     // fine
uint32.guard(123.4);    // TypeError: expected uint32

decimal.guard(1234);    // TypeError: expected decimal
decimal.guard(123.4);   // fine

answered Oct 15, 2015 at 8:16

How do you check if a number has a decimal in javascript?

schirrmacherschirrmacher

2,2812 gold badges27 silver badges29 bronze badges

You can multiply it by 10 and then do a "modulo" operation/divison with 10, and check if result of that two operations is zero. Result of that two operations will give you first digit after the decimal point. If result is equal to zero then the number is a whole number.

if ( (int)(number * 10.0) % 10 == 0 ){
// your code
}

answered Apr 5, 2017 at 7:48

How do you check if a number has a decimal in javascript?

BSevoBSevo

7435 silver badges13 bronze badges

function isDecimal(num) {
  return (num !== parseInt(num, 10));
}

answered Aug 4, 2017 at 15:34

How do you check if a number has a decimal in javascript?

Steve BrushSteve Brush

2,7311 gold badge21 silver badges15 bronze badges

You can use the bitwise operations that do not change the value (^ 0 or ~~) to discard the decimal part, which can be used for rounding. After rounding the number, it is compared to the original value:

function isDecimal(num) {
  return (num ^ 0) !== num;
}

console.log( isDecimal(1) ); // false
console.log( isDecimal(1.5) ); // true
console.log( isDecimal(-0.5) ); // true

answered Feb 23, 2018 at 16:19

How do you check if a number has a decimal in javascript?

makovkastarmakovkastar

4,9602 gold badges29 silver badges49 bronze badges

function isWholeNumber(num) {
  return num === Math.round(num);
}

answered Apr 1, 2019 at 13:52

How do you check if a number has a decimal in javascript?

Perhaps this works for you?

It uses regex to check if there is a comma in the number, and if there is not, then it will add the comma and stripe.

var myNumber = '50';
function addCommaStripe(text){
    if(/,/.test(text) == false){
        return text += ',-';
    } else {
        return text;
    }
}
myNumber = addCommaStripe(myNumber);

answered Jun 6, 2019 at 11:09

3

When using counters with decimal steps, checking if number is round will actually fail, as shown below. So it might be safest (although slow) to format the number with 9 (could be more) decimal places, and if it ends with 9 zeros, then it's a whole number.

const isRound = number => number.toFixed(9).endsWith('000000000');

for (let counter = 0; counter < 2; counter += 0.1) {
  console.log({ counter, modulo: counter % 1, formatted: counter.toFixed(9), isRound: isRound(counter) });
}

answered Jun 7, 2021 at 16:50

Function for check number is Decimal or whole number

function IsDecimalExist(p_decimalNumber) {
    var l_boolIsExist = true;

    if (p_decimalNumber % 1 == 0)
        l_boolIsExist = false;

    return l_boolIsExist;
}

Tom Sabel

3,76632 silver badges44 bronze badges

answered Apr 28, 2016 at 6:56

How do you check if a number is a decimal or not?

You can multiply it by 10 and then do a "modulo" operation/divison with 10, and check if result of that two operations is zero. Result of that two operations will give you first digit after the decimal point. If result is equal to zero then the number is a whole number.

How do you check if a string has a decimal?

Python String isdecimal() Method The isdecimal() method returns TRUE if the string is nonempty and all characters in it are decimal characters. Otherwise, it returns FALSE.

How do you display decimals in JavaScript?

Use the toFixed() method to format a number to 2 decimal places, e.g. num. toFixed(2) . The toFixed method takes a parameter, representing how many digits should appear after the decimal and returns the result.

How do you check if number is a whole number in JS?

The Number. isInteger() method in JavaScript is used to check whether the value passed to it is an integer or not. It returns true if the passed value is an integer, otherwise, it returns false.