-7

I need to separate the whole number and decimal value. Representing both values as whole numbers.

For example, 1.24 would output:

Whole number: 1 Decimal: 24

Marcus Jones
  • 1
  • 1
  • 1
  • How are you getting the value to be converted? Is the input actually a `double` or a `String` or do you have to read user input, or what? – azurefrog Sep 13 '19 at 21:31

1 Answers1

0

Assuming that your input is String. You can use just use split and separate out the decimal and whole part. Though beware of Floating Point Precision Error.

See: Is floating point math broken?

If you want to be really precise. Use BigDecimal instead.

String decimalString = "46.88999999999999";
String[] decimalSplit = decimalString.split("\\.");
System.out.println("Decimal Number: " + decimalString);
System.out.println("Whole Number: " + decimalSplit[0]);
System.out.println("Decimal Part: " + decimalSplit[1]);

int wholePart = Integer.parseInt(decimalSplit[0]);
double decimalPart = Double.parseDouble("." + decimalSplit[1]);
System.out.println("\nWhole Part: " + wholePart);
System.out.println("Decimal Part: " + decimalPart);

Output:

Decimal Number: 46.88999999999999
Whole Number: 46
Decimal Part: 88999999999999

Whole Part: 46
Decimal Part: 0.88999999999999
Yoshikage Kira
  • 1,070
  • 1
  • 12
  • 20