printf, how to insert decimal point for integer

后端 未结 4 1349
一整个雨季
一整个雨季 2021-01-19 11:14

I have an UINT16 unsigned integer of say

4455, 312, 560 or 70.

How to use printf to insert a decimal point before the last two

4条回答
  •  不思量自难忘°
    2021-01-19 11:30

    with a int x1000 precision 1234123 -> 1234.123

    printf("%4d.%.3d\n", x / 1000, x % 1000);
    

    if you need to round to 2 decimal

    printf("%4d.%.2d\n", ((x+5)/10) / 100, ((x+5)/10) % 100);
    

    only tested with positive

    input        print
    000004       0.00
    000005       0.01
    
    000014       0.01
    000015       0.02
    
    000100       0.10
    000101       0.10
    
    000105       0.11
    000994       0.99
    000995       1.00
    ...
    

提交回复
热议问题