Java - 格式化数字以仅打印小数部分 [英] Java - Format number to print decimal portion only

查看:26
本文介绍了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));

这篇关于Java - 格式化数字以仅打印小数部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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