简体   繁体   English

Java - 仅打印小数部分的格式编号

[英]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? 在Java中有一种简单的方法来格式化十进制,浮点数,双精度等只能打印数字的小数部分吗? 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. 我目前正在使用String.indexOf(“。”)方法与String.substring()方法结合来​​挑选小数点右侧的数字部分。 Is there a cleaner way to do this? 有更清洁的方法吗? Couldn't find anything in the DecimalFormat class or the printf method. 在DecimalFormat类或printf方法中找不到任何内容。 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. 您可以通过将double转换为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));

Divide by 1 and get remainder to get decimal portion (using "%"). 除以1得到余数得到小数部分(使用“%”)。 Use DecimalFormat to format result (using "#" symbol to suppress leading 0s): 使用DecimalFormat格式化结果(使用“#”符号来抑制前导0):

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

this prints .22 这打印.22

This will print 0.3 这将打印0.3

double x = 23.8;
int y =(int)x;
float z= (float) (x % y);
System.out.println(z);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM