Built in methods for displaying Significant figures

前端 未结 2 770
梦谈多话
梦谈多话 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.)

提交回复
热议问题