Use 1, not 2.

js> 2.3 % 1
0.2999999999999998
Answer from Ignacio Vazquez-Abrams on Stack Overflow
🌐
W3Schools
w3schools.com › js › js_numbers.asp
JavaScript Numbers
By default, JavaScript displays numbers as base 10 decimals.
🌐
Mikemcl
mikemcl.github.io › decimal.js
decimal.js API
number: integer, -9e15 to 0 inclusive Default value: -9e15 · The negative exponent limit, i.e. the exponent value below which underflow to zero occurs. If the Decimal to be returned by a calculation would have an exponent lower than minE then the value of that Decimal becomes zero. JavaScript numbers underflow to zero for exponents below -324.
🌐
W3Schools
w3schools.com › jsref › jsref_tofixed.asp
JavaScript toFixed() Method
The toFixed() method rounds the string to a specified number of decimals.
🌐
Adripofjavascript
adripofjavascript.com › blog › drips › avoiding-problems-with-decimal-math-in-javascript.html
Avoiding Problems with Decimal Math in JavaScript - A Drip of JavaScript
In JavaScript all numbers are IEEE 754 floating point numbers. Due to the binary nature of their encoding, some decimal numbers cannot be represented with perfect accuracy. This is analagous to how the fraction 1/3 cannot be accurately represented with a decimal number with a finite number ...
Find elsewhere
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › data types
Numbers
There’s just no way to store exactly 0.1 or exactly 0.2 using the binary system, just like there is no way to store one-third as a decimal fraction. The numeric format IEEE-754 solves this by rounding to the nearest possible number.
🌐
GitHub
github.com › MikeMcl › decimal.js
GitHub - MikeMcl/decimal.js: An arbitrary-precision Decimal type for JavaScript · GitHub
// Precision loss from using numeric literals with more than 15 significant digits. new Decimal(1.0000000000000001) // '1' new Decimal(88259496234518.57) // '88259496234518.56' new Decimal(99999999999999999999) // '100000000000000000000' // Precision loss from using numeric literals outside the range of Number values. new Decimal(2e+308) // 'Infinity' new Decimal(1e-324) // '0' // Precision loss from the unexpected result of arithmetic with Number values. new Decimal(0.7 + 0.1) // '0.7999999999999999' As with JavaScript numbers, strings can contain underscores as separators to improve readability.
Author   MikeMcl
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Numbers_and_strings
Numbers and strings - JavaScript | MDN
Decimal literals can start with a zero (0) followed by another decimal digit, but if all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number.
🌐
npm
npmjs.com › package › decimal.js › v › 10.4.3
decimal.js - npm
// Precision loss from using numeric literals with more than 15 significant digits. new Decimal(1.0000000000000001) // '1' new Decimal(88259496234518.57) // '88259496234518.56' new Decimal(99999999999999999999) // '100000000000000000000' // Precision loss from using numeric literals outside the range of Number values. new Decimal(2e+308) // 'Infinity' new Decimal(1e-324) // '0' // Precision loss from the unexpected result of arithmetic with Number values. new Decimal(0.7 + 0.1) // '0.7999999999999999' As with JavaScript numbers, strings can contain underscores as separators to improve readability.
      » npm install decimal.js
    
Published   Jul 06, 2025
Version   10.4.3
Author   Michael Mclaughlin
🌐
GitHub
github.com › tc39 › proposal-decimal
GitHub - tc39/proposal-decimal: Built-in exact decimal numbers for JavaScript · GitHub
Historically, JavaScript may not ... numbers were created. In some application architectures, JS only deals with a string representing a human-readable decimal quantity (e.g, "1.25"), and never does calculations or conver...
Author   tc39
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-get-decimal-portion-of-a-number-using-javascript
How to get decimal portion of a number using JavaScript ? | GeeksforGeeks
May 30, 2024 - The toFixed() method formats a number using fixed-point notation and returns a string representation of the number. This method can be useful for obtaining the exact decimal part of a number by specifying the number of digits after the decimal point.
🌐
Medium
medium.com › @riteshsinha_62295 › front-end-dilemmas-tackling-precision-problems-in-javascript-with-decimal-js-c38a9ae24ddd
Front-End Dilemmas: Tackling Precision Problems in JavaScript with Decimal.js | by Ritesh Sinha | Medium
September 15, 2023 - Wait, what? I expected the result to be 0.3, not this long, seemingly inaccurate number! JavaScript uses binary floating-point arithmetic, which can't represent some decimal fractions exactly.
🌐
W3docs
w3docs.com › javascript
How to Format a Number with Two Decimals in JavaScript
const formatter = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2, }); console.log(formatter.format(3.005)); // "3.01" console.log(formatter.format(2.345)); // "2.35" ... The alternative of the above method is the toLocaleString method which internally uses the Intl API: ... const format = (num, decimals) => num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2, }); console.log(format(3.005)); // "3.01" console.log(format(2.345)); // "2.35"
Top answer
1 of 14
625

You could use...

  • Math.trunc() (truncate fractional part, also see below)
  • Math.floor() (round down)
  • Math.ceil() (round up)
  • Math.round() (round to nearest integer)

...dependent on how you wanted to remove the decimal.

Math.trunc() isn't supported on all platforms yet (namely IE), but you could easily use a polyfill in the meantime.

Another method of truncating the fractional portion with excellent platform support is by using a bitwise operator (.e.g |0). The side-effect of using a bitwise operator on a number is it will treat its operand as a signed 32bit integer, therefore removing the fractional component. Keep in mind this will also mangle numbers larger than 32 bits.


You may also be talking about the inaccuracy of decimal rounding with floating point arithmetic.

Required Reading - What Every Computer Scientist Should Know About Floating-Point Arithmetic.

2 of 14
108

You can also use bitwise operators to truncate the decimal.

e.g.

let x = 9 / 2;
console.log(x); // 4.5

x = ~~x;
console.log(x); // 4

x = -3.7
console.log(~~x) // -3
console.log(x | 0) // -3
console.log(x << 0) // -3

Bitwise operations are considerably more efficient than the Math functions. The double not bitwise operator also seems to slightly outperform the x | 0 and x << 0 bitwise operations by a negligible amount.

// 952 milliseconds
for (var i = 0; i < 1000000; i++) {
    (i * 0.5) | 0;
}

// 1150 milliseconds
for (var i = 0; i < 1000000; i++) {
    (i * 0.5) << 0;
}

// 1284 milliseconds
for (var i = 0; i < 1000000; i++) {
    Math.trunc(i * 0.5);
}

// 939 milliseconds
for (var i = 0; i < 1000000; i++) {
    ~~(i * 0.5);
}

Also worth noting is that the bitwise not operator takes precedence over arithmetic operations, so you may need to surround calculations with parentheses to have the intended result:

const x = -3.7

console.log(~~x * 2) // -6
console.log(x * 2 | 0) // -7
console.log(x * 2 << 0) // -7

console.log(~~(x * 2)) // -7
console.log(x * 2 | 0) // -7
console.log(x * 2 << 0) // -7

More info about the double bitwise not operator can be found at Double bitwise NOT (~~)

You also should ensure that your integer will not need more than 32-bits to represent:

const a = 0x100000000 + 0.1; // 4294967296.1
console.log(Math.trunc(a)); // 4294967296
console.log(~~a); // 0

Top answer
1 of 3
158
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

2 of 3
52

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;
};