Java - 格式化数字以仅打印小数部分

2022-01-15 00:00:00 format decimal numbers java

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.

解决方案

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

相关文章