Round a double to 3 significant figures

前端 未结 6 1137
伪装坚强ぢ
伪装坚强ぢ 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:07

    how I can round a double value to 3 significant figures

    You can't. Doubles are representing in binary. They do not have decimal places to be rounded to. The only way you can get a specific number of decimal places is to convert it to a decimal radix and leave it there. The moment you convert it back to double you have lost the decimal precision again.

    For all the fans, here and elsewhere, of converting to other radixes and back, or multiplying and dividing by powers of ten, please display the resulting double value % 0.001 or whatever the required precision dictates, and explain the result.

    EDIT: Specifically, the proponents of those techniques need to explain the 92% failure rate of the following code:

    public class RoundingCounterExample
    {
        static float roundOff(float x, int position)
        {
            float a = x;
            double temp = Math.pow(10.0, position);
            a *= temp;
            a = Math.round(a);
            return (a / (float)temp);
        }
    
        public static void main(String[] args)
        {
            float a = roundOff(0.0009434f,3);
            System.out.println("a="+a+" (a % .0001)="+(a % 0.001));
            int count = 0, errors = 0;
            for (double x = 0.0; x < 1; x += 0.0001)
            {
                count++;
                double d = x;
                int scale = 2;
                double factor = Math.pow(10, scale);
                d = Math.round(d * factor) / factor;
                if ((d % 0.01) != 0.0)
                {
                    System.out.println(d + " " + (d % 0.01));
                    errors++;
                }
            }
            System.out.println(count + " trials " + errors + " errors");
        }
    }
    

提交回复
热议问题