Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Format number to print decimal portion only

Is there a simple way in Java to format a decimal, float, double, etc to ONLY print the decimal portion of the number? I do not need the integer portion, even/especially if it is zero! I am currently using the String.indexOf(".") method combined with the String.substring() method to pick off the portion of the number on the right side of the decimal. Is there a cleaner way to do this? Couldn't find anything in the DecimalFormat class or the printf method. Both always return a zero before the decimal place.

like image 241
Fred Avatar asked Apr 07 '11 16:04

Fred


People also ask

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.

What is .2f in Java?

2f", value); The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (. 2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).

How do you do 2 decimal places in Java?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places. /* Code example to print a double to two decimal places with Java printf */ System.

How do I limit decimal places in Java double?

Using BigDecimal You can convert double or float to BigDecimal and use setScale() method to round double/float to 2 decimal places.


2 Answers

You can remove the integer part of the value by casting the double to a long. You can then subtract this from the original value to be left with only the fractional value:

double val = 3.5;
long intPartVal= (long) val;
double fracPartVal = val - intPartVal;
System.out.println(fracPartVal);

And if you want to get rid of the leading zero you can do this:

System.out.println(("" + fracPartVal).substring(1));
like image 179
jberg Avatar answered Sep 20 '22 10:09

jberg


Divide by 1 and get remainder to get decimal portion (using "%"). Use DecimalFormat to format result (using "#" symbol to suppress leading 0s):

double d1 = 67.22;
double d2 = d1%1;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(d2));

this prints .22

like image 43
CodeClimber Avatar answered Sep 23 '22 10:09

CodeClimber