Forcing BigDecimals to use scientific notation

后端 未结 4 1505
忘掉有多难
忘掉有多难 2020-12-06 08:34

I have this method:

    public void Example(BigDecimal value, int scale){
    BigDecimal x = new BigDecimal(\"0.00001\");
    System.out.println(\"result: \"         


        
4条回答
  •  离开以前
    2020-12-06 08:39

    Here is a version of DannyMo's answer that sets the scale automatically:

    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
    

提交回复
热议问题