Say we have a double value of 12345.6789
(should be dynamic)
Now the requirement is split the number and get the decimal digits and fractional digits, which would be:
double number = 12345.6789;
int decimal = 12345;
int fractional = 6789;
I get the decimal part work out but could you please give a hint on the fractional part? Thanks a lot.
FOLLOW ME You can convert the double value into a intvalue. int x = (int) y where y is your double variable. Then, printing x does not give decimal places (15000 instead of 15000.0).
Truncation Using Casting If our double value is within the int range, we can cast it to an int. The cast truncates the decimal part, meaning that it cuts it off without doing any rounding.
To get the decimal part you could do this: double original = 1.432d; double decimal = original % 1d; Note that due to the way that decimals are actually thought of, this might kill any precision you were after.
double number = 12345.6789; // you have this
int decimal = (int) number; // you have 12345
double fractional = number - decimal // you have 0.6789
The problem here is that the fractional part is not written in memory as "0.6789", but may have certain "offsets", so to say. For example 0.6789
can be stored as 0.67889999291293929991
.
I think your main concern here isn't getting the fractional part, but getting the fractional part with a certain precision.
If you'd like to get the exact values you assigned it to, you may want to consider this (altho, it's not a clean solution):
String doubleAsText = "12345.6789";
double number = Double.parseDouble(doubleAsText);
int decimal = Integer.parseInt(doubleAsText.split("\.")[0]);
int fractional = Integer.parseInt(doubleAsText.split("\.")[1]);
But, as I said, this is not the most efficient and cleanest solution.
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