I am trying to separate a double into the integer and decimal parts
So for example, the number 24.4 should be separated into 24 and 4.
int integer = (int)number;
double decimal = number-(int)number;
System.out.println(decimal);
Using this method gives me the following values :
integer = 24
decimal = 0.3999999999999986
I need the value of decimal to be 4.
How can this problem be fixed ?
4 INT and MOD functions. Yes we do have dedicated functions to get the integers and decimal parts of numbers in Excel. To get integers or whole part of a number use: =INT (A2) And to get the fractional or decimal part use: =MOD (A2,1)
First Approach: Splitting the String First of all, let's convert the decimal number to a String equivalent. Then we can split the String at the decimal point index. Let's understand this with an example: double doubleNumber = 24.04 ; String doubleAsString = String.valueOf (doubleNumber); int indexOfDecimal = doubleAsString.indexOf ( "."
To get integers or whole part of a number use: =INT(A2) And to get the fractional or decimal part use: =MOD(A2,1) But again we sucked in the same problem – decimal parts deprived of respective negative sign.
To split numbers (negative or positive) I use =TRUNC (A1,0) then to get the decimal =A1-A2 assuming =TRUNC (A1,0) is in cell A2. Woops - just saw Sam's post! Formulas to split positive decimal numbers are used to separate dates into days and hours.
You could do a String split(...)
. And then Integer parseInt(...)
to get back the two integer components.
This is because double
s aren't exactly "real numbers" - remember there are infinite number of real numbers in any range, while there are only finite number of digits in double
- thus finite number of values, so some round off must occure.
The fact is, 24.4 cannot be exactly represented by double
- so the fraction of your number really is something around 0.3999....
If you want an exact solution - you should use a library that gives you exact values for decimals, such as BigDecimal
.
If you want to understand more about this issue of double
s being not exact - you should read more about floating points arithmetics, and this article, though high level, is also a must in order to really understand what's going on.
If you cannot understand these article just yet - just take into consideration: If you need an exact value - double
s cannot provide it - and you should use a library if this is the case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With