Built in methods for displaying Significant figures

前端 未结 2 771
梦谈多话
梦谈多话 2021-01-19 16:48

There\'s been a lot of questions on rounding by significant figures, and answers that that provides a new method to do the rounding, such as:

Rounding to an arbitrar

相关标签:
2条回答
  • 2021-01-19 17:28

    I found this nice way of doing it using String format. Apparently, users can specify maximum number of significant digits with a string format 'g' or 'G'. (http://developer.android.com/reference/java/util/Formatter.html)

    This is if you just want to print it out.

    public String toSignificantFiguresString(BigDecimal bd, int significantFigures){
        return String.format("%."+significantFigures+"G", bd);
    }
    

    This is if you want to convert it:

    public BigDecimal toSignificantFigures(BigDecimal bd, int significantFigures){
        String s = String.format("%."+significantFigures+"G", bd);
        BigDecimal result = new BigDecimal(s);
        return result;
    }
    

    Here's an example of it in action:

        BigDecimal bd = toSignificantFigures(BigDecimal.valueOf(12345678.123456789), 10);
        System.out.println("bd: " + String.format("%f",bd));
    

    NB: I'm using BigDecimal for calculation because double and float has a precision problems.)

    0 讨论(0)
  • 2021-01-19 17:39

    Not quite right. To get it perfect:

    public String toSignificantFiguresString(BigDecimal bd, int significantFigures ){
        String test = String.format("%."+significantFigures+"G", bd);
        if (test.contains("E+")){
            test = String.format(Locale.US, "%.0f", Double.valueOf(String.format("%."+significantFigures+"G", bd)));
        }
        return test;
    }
    
    0 讨论(0)
提交回复
热议问题