Java - Format number to print decimal portion only

10,072

Solution 1

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

Solution 2

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

Share:
10,072
Fred
Author by

Fred

Updated on June 04, 2022

Comments

  • Fred
    Fred almost 2 years

    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.

  • Fred
    Fred about 13 years
    I believe that will still print the leading zero. I need it to print: .5, not 0.5.
  • mre
    mre about 13 years
    +1 this is new to me. here's another example.
  • jberg
    jberg about 13 years
    added in the way to remove the leading zero, but I believe it was more or less what you were already doing. Subtracting to remove the integer part of the number should still be a more attractive solution though, I think.
  • poolie
    poolie over 8 years
    This will work but it's unnecessarily complicated. Simply taking the remainder modulo 1 will do, or subtracting the whole integer part.