Java - Format number to print decimal portion only

后端 未结 3 1629
隐瞒了意图╮
隐瞒了意图╮ 2020-12-19 06:41

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

相关标签:
3条回答
  • 2020-12-19 07:04

    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

    0 讨论(0)
  • 2020-12-19 07:06

    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));
    
    0 讨论(0)
  • 2020-12-19 07:19

    This will print 0.3

    double x = 23.8;
    int y =(int)x;
    float z= (float) (x % y);
    System.out.println(z);
    
    0 讨论(0)
提交回复
热议问题