Jack
Jack

Reputation: 497

Split number into an integer and decimal

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

Upvotes: 2

Views: 4937

Answers (2)

TechTrip
TechTrip

Reputation: 4537

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

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

Your program's logic is correct. The problem is the representation that you have selected for your input.

double is inherently imprecise, so the lower-order digits are often not represented correctly. To fix this problem, you could use BigDecimal or even a String data type.

If you use BigDecimal, simply rewrite your algorithm using the methods of BigDecimal. If you use String, split user input at the decimal point, and add required zeros and decimal points after the whole part and before the fractional part.

Upvotes: 1

Related Questions