serene
serene

Reputation: 1646

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

Like in php, there is a function - list($whole, $decimal) = explode('.', $mynumber); which separates both decimal and whole number.(like mynumber is 4.6)

How can we get it in react native.

Upvotes: 1

Views: 4855

Answers (2)

TKoL
TKoL

Reputation: 13892

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

Upvotes: 2

Drew Reese
Drew Reese

Reputation: 202605

You can convert a value to a string and split on '.'

String(value).split('.')

Below snippet is a function that can take either a string or a number, split, and return an array of numbers instead of strings.

const getWholeAndDecimal = value => {
  const [whole, decimal] = String(value).split('.');
  return [Number(whole), Number(decimal)];
}

console.log(getWholeAndDecimal(13.37)); // [13, 37]
console.log(getWholeAndDecimal('13.37')); // [13, 37]

const [whole, decimal] = getWholeAndDecimal(13.37);
console.log(`whole: ${whole}, decimal: ${decimal}`);

But this doesn't really guard against NaNs so here's a version with guard function.

const getWholeAndDecimal = value => {
  const guardNaN = value => isFinite(value) ? value : 0;
  const [whole, decimal] = String(value).split('.');
  return [Number(guardNaN(whole)), Number(guardNaN(decimal))];
}

console.log(getWholeAndDecimal(13.37)); // [13, 37]
console.log(getWholeAndDecimal('13.37')); // [13, 37]
console.log(getWholeAndDecimal('1337')); // [1337, 0]

Upvotes: 2

Related Questions