-2

I've recently got into Java and I wanted to ask how to extract just the decimal section in order to use that for further calculations

My code basically converts kilometers to miles, and the user inputs the kilometers (so the value is not fixed)

E.G the user inputs 6KM which turns it into 3.728miles. I wanted to extract the .728 so I can convert the decimal miles into yards (E.G 3 Miles and approximately 1281 Yards).

I have downcasted this with
int wholeMileConversion = (int)conversionOutput; which gives me 3

But I don't know how to extract JUST THE DECIMALS in order to do: wholeYardConversion = decimalOnlyValue * yards

Sorry if it's hard to understand, I will try to explain again if I can.

Fangx
  • 1
  • 1

1 Answers1

0

Try this:

double v = 3.287;
double decimalPart = v % 1;

% is the remainder operator. So 10 % 3 == 1. But it also works for doubles.
So the remainder of 2.5 % 1 would be .5 But remember that double values are not going to be exactly what they appear to be due to limited width of 64 bits and that most decimal values have a repeating component. I.e. they don't have a finite decimal expansion.

WJS
  • 36,363
  • 4
  • 24
  • 39
  • Thank you, based on what you said. I did something similar and got what I wanted! I basically used what you said in terms of users input and did double extractDecimalValue = conversionOutput % 1; | double calculateYards = extractDecimalValue * yards; | int wholeYards = (int)calculateYards; – Fangx Nov 09 '20 at 19:34