Get Decimal Portion of a Number with JavaScript

Get decimal portion of a number with JavaScript

Use 1, not 2.

js> 2.3 % 1
0.2999999999999998

how to get whole and decimal part of a number in react native

This is more of a javascript question than a react question.

First of all, it depends on whether your number is actually a number or a string. However, you can force it to be one or the other anyway.

If it's a string, you can do something similar to PHP. You can split it on the decimal, [whole, dec] = num.split('.') -- this makes whole and dec variables hold their respective (string) values that you want.

If it's a number, you could maybe round the number to the next lower integer, then subtract the rounded number from the original number to get the decimal portion.

x = 1.2;
rounded = Math.floor(x);
decimal = x - rounded;

Funnily enough, that exact example produces an issue because of floating-point numbers - the result expected would be 0.2, but javascript spits out 0.19999999999999996

Check if a number has a decimal place/is a whole number

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

Simplest way of getting the number of decimals in a number in JavaScript

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

Get Number of Decimal Places with Javascript

Like this:

var val = 37.435345;
var countDecimals = function(value) {
let text = value.toString()
// verify if number 0.000005 is represented as "5e-6"
if (text.indexOf('e-') > -1) {
let [base, trail] = text.split('e-');
let deg = parseInt(trail, 10);
return deg;
}
// count decimals for number in representation like "0.123456"
if (Math.floor(value) !== value) {
return value.toString().split(".")[1].length || 0;
}
return 0;
}
countDecimals(val);

Show decimal value of counter

You can try using toFixed():

The toFixed() method formats a number using fixed-point notation.

jQuery('.count').each(function () {
jQuery(this).prop('Counter',0).animate({
Counter: jQuery(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
if(this.id == 'reducedaily'){
jQuery(this).text(now.toFixed(1));
}
else{
jQuery(this).text(now.toFixed(0));
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="shiva"><span class="count">200</span></div>
<div id="shiva2"><span class="count" id="reducedaily">4.7</span></div>

How can I remove the decimal part from JavaScript number?

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.

JS decimal number problem need a function similar to toFixed()

You could take the logarithm of 10 and adjust smaller numbers.

const
fix = v => v > 0.01
? v.toFixed(2)
: v.toFixed(1 - Math.floor(Math.log10(Math.abs(v))));

console.log([20.3698, 0.36587, 0.000014247, 0.00000000008824721, 0.0000000000099879].map(fix));


Related Topics



Leave a reply



Submit