Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf, how to insert decimal point for integer

Tags:

c

printf

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.

like image 918
riscy Avatar asked Dec 12 '22 11:12

riscy


1 Answers

%.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));
like image 56
Yu Hao Avatar answered Dec 22 '22 04:12

Yu Hao