简体   繁体   中英

printf, how to insert decimal point for integer

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 digits so the example numbers appear as

44.55, 3.12, 5.60 or 0.70

If there is no printf solution, is there another solution for this?

I do not wish to use floating point.

%.2d could add the extra padding zeros

printf("%d.%.2d", n / 100, n % 100);

For example, if n is 560 , the output is: 5.60

EDIT : I didn't notice it's UINT16 at first, according to @Eric Postpischil's comment, it's better to use:

printf("%d.%.2d", (int) (x/100), (int) (x%100));
printf("%d.%.2d", x / 100, x % 100);

You can use printf directly with out using float

printf("%d.%02d", num/100, num%100);

%02d means right align with zero padding.

if num is 4455 ==>output is 44.55  
if num is 203  ==>output is 2.03

EDIT:
by seeing comment from @ Eric Postpischil , it's better to use like this.

printf("%d.%02d", (int) (num/100), (int) (num%100));

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
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM