Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract fractional digits of double/BigDecimal [duplicate]

Tags:

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.

like image 429
Dreamer Avatar asked Jul 15 '12 20:07

Dreamer


People also ask

How do you remove the decimal part of a double in Java?

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).

How do you get rid of decimal point in double value?

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.

How do you extract the decimal part of a number in Java?

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.


1 Answers

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.

like image 86
ioreskovic Avatar answered Oct 16 '22 14:10

ioreskovic