使用最多五位总数格式化双精度值,必要时舍入十进制数字 [英] Format double values using a maximum of five total digits, rounding decimal digits if necessary

查看:161
本文介绍了使用最多五位总数格式化双精度值,必要时舍入十进制数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 double 值,我想将其转换为 String 值,并具有以下格式限制:

I have double values which I would like to convert to String values with the following format restrictions:


number_of_fraction_digits = max(0,5-number_of_integer_digits)

number_of_fraction_digits = max( 0, 5 - number_of_integer_digits )

基本上我想在可能的情况下将位数保持为5,必要时舍入十进制数字。例如:

Essentially I want to keep the number of digits to 5 if possible, rounding decimal digits if necessary. For example:


 float          String
-------------------------
     1               1
   100             100
100000          100000
 99999           99999
 99999.99        99999
  9999.99         9999.9
   999.99          999.99
    23.34324        23.343

我研究过使用DecimalFormat 但据我所知,它并没有完全实现我所追求的目标。

I've looked into using DecimalFormat but as far as I can tell it doesn't quite accomplish what I'm after.

它允许使用 setMaximumFractionDigits()设置最大小数位数,但据我所知,我必须计算整数个数数字,并自己执行上述计算。

It allows setting of the maximum number of decimal digits using setMaximumFractionDigits() but as far as I can tell I would have to calculate the number of integer digits and perform the above calculation myself.

所以基本的问题是,是否有一种漂亮,干净的内置方式来格式化数字。

So the basic question is whether there is a nice, clean built-in way to format numbers in this way.

推荐答案

public class SignificantFormat {

    public static String formatSignificant(double value, int significant)
    {
        MathContext mathContext = new MathContext(significant, RoundingMode.DOWN);
        BigDecimal bigDecimal = new BigDecimal(value, mathContext);
        return bigDecimal.toPlainString();
    }

    public static void main(String[] args) {
        double[] data = { 1, 100, 100000, 99999, 99999.99, 9999.99, 999.99, 23.34324 };
        for(double d: data){
            System.out.printf("Input: %10s \tOutput: %10s\n", Double.toString(d), formatSignificant(d, 5));
        }
    }
}

这篇关于使用最多五位总数格式化双精度值,必要时舍入十进制数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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