Built in methods for displaying Significant figures

ぐ巨炮叔叔 提交于 2019-12-04 04:09:25

问题


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 arbitrary number of significant digits

Round a double to 2 decimal places

Most of these questions and solutions are around 2009~2010.

I want to have a simple built in method (or from standard well know libraries such as from Apache or Spring) that given the number and significant figures, prints out the number limited to the specified significant figure.

Ie:

  • 123.456789 // to 2 signficant figures: 120
  • 123.456789 // to 4 signficant figures: 123.4
  • 123.456789 // to 7 signficant figures: 123.4567

回答1:


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.)




回答2:


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;
}


来源:https://stackoverflow.com/questions/19487506/built-in-methods-for-displaying-significant-figures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!