Input 23.893 would become INTEGER - 23, DECIMAL - 0.893
Here's the key snippet from my code
double realNumber = scan.nextDouble(); \\store the keyboard input in variable realNumber
double integerPart = Math.floor(realNumber); \\round down eg. 23.893 --> 23
double fractionPart = realNumber - integerPart; \\find the remaining decimal
When I try this with long numbers the decimal part differs slightly from the actual.
Input - 234.324112341234134 becomes INTEGER - 234.0,
DECIMAL - 0.3241123412341267
As stated by @dasblinkenlight you can use methods from BigDecimal and combine them with a splitter. I wouldn't count the decimal points though, easier to stick with BigDecimal.
For example:
public static void main(String[] args) {
String realNumber = "234.324823783782";
String[] mySplit = realNumber.split("\\.");
BigDecimal decimal = new BigDecimal(mySplit[0]);
BigDecimal real = new BigDecimal(realNumber);
BigDecimal fraction = real.subtract(decimal);
System.out.println(String.format("Decimal : %s\nFraction: %s", decimal.toString(),fraction.toString()));
}
This outputs the following: Decimal : 234 Fraction: 0.324823783782
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments