Java格式的双倍特定位数忽略零
问题描述:
我想将某些双精度值格式化为忽略起始零的特定位数。Java格式的双倍特定位数忽略零
实施例,让我们说格式6个位数:
131.468627436358 -> 131.469
3.16227766016838 -> 3.16228
0.66018099039325 -> 0.660181
0.02236067977499 -> 0.0223607
答
BigDecimal的正确允许显著数字处理。这:
MathContext round3SigFig = new MathContext(3,RoundingMode.HALF_UP);
System.out.println((new BigDecimal(0.000923874932)).round(round3SigFig));
生产:
0.000924
显然,虽然经过一个任意精度的对象表示通过你的浮点不理想。
答
将此视为最后一次机会选项:如何将数字转换为字符串,将前六位数字转换为“,”并将其转换为double。
答
我相信这是密切相关的以下问题:Format double values using a maximum of five total digits, rounding decimal digits if necessary
有一个在我链接的问题的答案,它采用MathContext
和BigDecimal
(如maybeWeCouldStealAVan的答案)。然而,这并不适合我,因为我关心总位数。不过,它可能适用于你。
我最终编写了自己的自定义解决方案,其格式与我所需的完全一致。也许这也符合您的要求,或者可以很容易地修改以满足它们:
public static String format(double value, int totalDigits)
{
String s = String.valueOf(value);
int decimal = s.indexOf('.');
// there is no decimal part, so simply return the String
if (decimal == -1)
{
return s;
}
else
{
int finalLength;
// example: 23.34324
// the final result will be length totalDigits + 1 because we will include the decimal
if (decimal < totalDigits)
{
finalLength = totalDigits + 1;
}
// example: 99999
// the final result will be length totalDigits because there will be no decimal
else if (decimal == totalDigits)
{
finalLength = totalDigits;
}
// example: 999999.999
// we can't make the final length totalDigits because the integer portion is too large
else
{
finalLength = decimal;
}
finalLength = Math.min(s.length(), finalLength);
return s.substring(0, finalLength);
}
}
public static void main(String[] args)
{
double[] data = { 1, 100, 1000, 10000, 100000, 99999, 99999.99, 9999.99, 999.99, 23.34324, 0.111111 };
for (double d : data)
{
System.out.printf("Input: %10s \tOutput: %10s\n", Double.toString(d), format(d, 5));
}
}
答
使用对数函数来计算您需要的附加位数。
public static int leadingZeros (double d) {
return (d >= 1.0) ? 0 : (int) (-1 * (Math.floor (Math.log (d)/Math.log (10))));
}
对于
System.out.println (leadingZeros (4));
System.out.println (leadingZeros (0.4));
System.out.println (leadingZeros (0.04));
System.out.println (leadingZeros (0.004));
它返回0,1,2,3
['java.text.DecimalFormat'](http://docs.oracle.com/javase/ 6 /文档/ API/JAVA /文本/ DecimalFormat.html) – 2012-04-22 20:04:21