Moving decimal places over in a double

后端 未结 9 1086
别跟我提以往
别跟我提以往 2020-11-22 16:18

So I have a double set to equal 1234, I want to move a decimal place over to make it 12.34

So to do this I multiply .1 to 1234 two times, kinda like this

<         


        
9条回答
  •  無奈伤痛
    2020-11-22 16:51

    Yes, there is. With each double operation you may lose accuracy but the amount of accuracy differs for each operation and can be minimized by choosing the right sequence of operations. For example when multiplying set of numbers, it is best to sort set by exponent before multiplying.

    Any decent book on number crunching describes this. For example: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

    And to answer your question:

    Use divide instead of multiply, this way you get correct result.

    double x = 1234;
    for(int i=1;i<=2;i++)
    {
      x =  x / 10.0;
    }
    System.out.println(x);
    

提交回复
热议问题