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

发布于 2024-10-31 13:44:16 字数 209 浏览 7 评论 0原文

Java中有没有一种简单的方法来格式化小数、浮点数、双精度数等以仅打印数字的小数部分?我不需要整数部分,即使/特别是如果它为零! 我目前正在使用 String.indexOf(".") 方法与 String.substring() 方法相结合来选取小数点右侧的数字部分。有没有更干净的方法来做到这一点?在 DecimalFormat 类或 printf 方法中找不到任何内容。两者都始终在小数点前返回零。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

面如桃花 2024-11-07 13:44:16

您可以通过将 double 转换为 long 来删除该值的整数部分。然后,您可以从原始值中减去它,只留下小数值:

double val = 3.5;
long intPartVal= (long) val;
double fracPartVal = val - intPartVal;
System.out.println(fracPartVal);

如果您想去掉前导零,您可以这样做:

System.out.println(("" + fracPartVal).substring(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));
澜川若宁 2024-11-07 13:44:16

除以1并取余即可得到小数部分(使用“%”)。使用 DecimalFormat 格式化结果(使用“#”符号抑制前导 0):

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

这将打印 .22

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

我为君王 2024-11-07 13:44:16

这将打印 0.3

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

This will print 0.3

double x = 23.8;
int y =(int)x;
float z= (float) (x % y);
System.out.println(z);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文