【问题标题】:Forcing BigDecimals to use scientific notation强制 BigDecimals 使用科学记数法
【发布时间】:2013-08-02 22:30:00
【问题描述】:

我有这个方法:

    public void Example(BigDecimal value, int scale){
    BigDecimal x = new BigDecimal("0.00001");
    System.out.println("result: " + (value.multiply(x)).setScale(scale, RoudingMode.HALF_UP).toString());

例如,如果 value = 1 且 scale = 2,则输出为“result: 0.00”。我以为会是 1.00E-5。所以,我的疑问是:如果 BigDecimal 的比例大于某个值(在我的示例中为 2),我如何强制它以科学记数法格式化?

【问题讨论】:

  • 为什么不使用自己的toStringtoEngineeringStringmethods?
  • @PM77-1:两者都总是使用科学记数法。而工程符号并不总是科学符号。
  • @PM 因为,对于我正在做的事情,我需要它是科学符号,而不是工程...
  • 这可能不是很有帮助,但这里有一种打印方式1.0E-5:x.doubleValue()
  • 您可以使用基本数学来计算。 (num / pow(10, floor(log(num))) + "E" + floor(log(num)).

标签: java bigdecimal


【解决方案1】:

这是自动设置比例的 DannyMo 答案的一个版本:

private static String format(BigDecimal x)
{
    NumberFormat formatter = new DecimalFormat("0.0E0");
    formatter.setRoundingMode(RoundingMode.HALF_UP);
    formatter.setMinimumFractionDigits((x.scale() > 0) ? x.precision() : x.scale());
    return formatter.format(x);
}

System.out.println(format(new BigDecimal("0.01")));   // 1.0E-2
System.out.println(format(new BigDecimal("0.001")));  // 1.0E-3
System.out.println(format(new BigDecimal("500")));    // 5E2
System.out.println(format(new BigDecimal("500.05"))); // 5.00050E2

【讨论】:

    【解决方案2】:

    您可以将DecimalFormatsetMinimumFractionDigits(int scale) 一起使用:

    private static String format(BigDecimal x, int scale) {
      NumberFormat formatter = new DecimalFormat("0.0E0");
      formatter.setRoundingMode(RoundingMode.HALF_UP);
      formatter.setMinimumFractionDigits(scale);
      return formatter.format(x);
    }
    ...
    System.out.println(format(new BigDecimal("0.00001"), 2)); // 1.00E-5
    System.out.println(format(new BigDecimal("0.00001"), 3)); // 1.000E-5
    

    【讨论】:

    • 但是如果 scale 的值发生了变化呢?我该如何处理?
    • 请参阅下面的自动设置比例的版本。
    • 注意:DecimalFormat 只处理可以表示为双精度数的数字。尝试格式化 BigDecimal("1e400"),它会给你“∞”。
    【解决方案3】:

    你可以使用这样的东西:

    int maxScale = 2;
    
    BigDecimal value = BigDecimal.ONE;
    BigDecimal x = new BigDecimal("0.00001");
    BigDecimal result = value.multiply(x);
    
    if (result.scale() > maxScale) {
        System.out.format("result: %.2E\n", result); // You can change .2 to the value you need
    } else {
        System.out.println("result: " + result.toPlainString());
    }
    

    【讨论】:

      【解决方案4】:

      试试 DecimalFormat 类。它具有用于双精度和长数字方法的格式方法,因此您应该执行以下操作:

      BigDecimal x = new BigDecimal("0.00001");
      DecimalFormat frmt = new DecimalFormat("0.00E00");
      String formatted = frmt.format(x.doubleValue());
      System.out.println("result: " + formatted);
      

      DecimalFormat javadoc

      【讨论】:

      • 将大小数移动到双精度可能会弄乱值。这不是解决方案。
      猜你喜欢
      • 1970-01-01
      • 2018-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 2019-08-13
      • 1970-01-01
      相关资源
      最近更新 更多