Moving decimal places over in a double

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

    This is caused by the way computers store floating-point numbers. They don't do so exactly. As a programmer, you should read this floating-point guide to familiarize yourself with the trials and tribulations of handling floating-point numbers.

    0 讨论(0)
  • 2020-11-22 17:06

    No, as Java floating point types (indeed all floating point types) are a trade-off between size and precision. While they're very useful for a lot of tasks, if you need arbitrary precision, you should use BigDecimal.

    0 讨论(0)
  • 2020-11-22 17:15

    In financial software it is common to use integers for pennies. In school, we were taught how to use fixed-point instead of floating, but that is usually powers of two. Storing pennies in integers might be called "fixed point" as well.

    int i=1234;
    printf("%d.%02d\r\n",i/100,i%100);
    

    In class, we were asked in general what numbers can be exactly represented in a base.

    For base=p1^n1*p2^n2... you can represent any N where N=n*p1^m1*p2^m2.

    Let base=14=2^1*7^1... you can represent 1/7 1/14 1/28 1/49 but not 1/3

    I know about financial software -- I converted Ticketmaster's financial reports from VAX asm to PASCAL. They had their own formatln() with codes for pennies. The reason for the conversion was 32 bit integers were no longer enough. +/- 2 billion pennies is $20 million and that overflowed for the World Cup or Olympics, I forgot.

    I was sworn to secrecy. Oh well. In academea, if it's good you publish; in industry, you keep it secret.

    0 讨论(0)
提交回复
热议问题