Moving decimal places over in a double

后端 未结 9 985
别跟我提以往
别跟我提以往 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 17:01

    Funny that numerous posts mention to use BigDecimal but no-one bothers to give the correct answer based on BigDecimal? Because even with BigDecimal, you can still go wrong, as demonstrated by this code

    String numstr = "1234";
    System.out.println(new BigDecimal(numstr).movePointLeft(2));
    System.out.println(new BigDecimal(numstr).multiply(new BigDecimal(0.01)));
    System.out.println(new BigDecimal(numstr).multiply(new BigDecimal("0.01")));
    

    Gives this output

    12.34
    12.34000000000000025687785232264559454051777720451354980468750
    12.34
    

    The BigDecimal constructor specifically mentions that it is better to use String constructor than a numeric constructor. Ultimate precision is also influenced by the optional MathContext.

    According to the BigDecimal Javadoc it is possible to create a BigDecimal which is exactly equal to 0.1, provided you use the String constructor.

提交回复
热议问题