Round a double to 3 significant figures

前端 未结 6 1161
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 10:15

Does anybody know how I can round a double value to 3 significant figures like the examples on this website

http://www.purplemath.com/modules/rounding2.htm

6条回答
  •  生来不讨喜
    2020-12-10 11:18

    I usually don't round the number itself but round the String representation of the number when I need to display it because usually it's the display that matters, that needs the rounding (although this may not be true in situations, and perhaps yours, but you need to elaborate on this if so). This way, my number retains its accuracy, but it's display is simplified and easier to read. To do this, one can use a DecimalFormat object, say initialzed with a "0.000" String (new DecimalFormat("0.000")), or use String.format("%.3f", myDouble), or several other ways.

    For example:

    // yeah, I know this is just Math.PI.
    double myDouble = 3.141592653589793;
    DecimalFormat myFormat = new DecimalFormat("0.000");
    String myDoubleString = myFormat.format(myDouble);
    System.out.println("My number is: " + myDoubleString);
    
    // or you can use printf which works like String.format:
    System.out.printf("My number is: %.3f%n", myDouble);
    

提交回复
热议问题