Java - 仅打印小数部分的格式编号 [英] Java - Format number to print decimal portion only

查看:162
本文介绍了Java - 仅打印小数部分的格式编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中有一种简单的方法来格式化小数,浮点数,双精度等,只打印数字的小数部分?我不需要整数部分,甚至/尤其是如果它是零!
我目前正在使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆