Java - 仅打印小数部分的格式编号 [英] Java - Format number to print decimal portion only
问题描述
我目前正在使用String.indexOf(。)方法结合String.substring()方法来挑选小数部分右边的数字部分。有没有更干净的方法来做到这一点?在DecimalFormat类或printf方法中找不到任何东西。两者总是在小数点前面返回一个零。
您可以通过将double转换为长。您可以从原始值中减去这个值,只剩下小数值:
double val = 3.5;
long intPartVal =(long)val;
double fracPartVal = val - intPartVal;
System.out.println(fracPartVal);
如果你想摆脱前面的零,你可以这样做:
System.out.println((+ fracPartVal).substring(1));
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));
这篇关于Java - 仅打印小数部分的格式编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!