Printf, how to insert a decimal point for an integer

I have a UINT16 unsigned integer

 4455, 312, 560 or 70. 

How to use printf to insert a decimal point to the last two digits so that the example numbers display as

 44.55, 3.12, 5.60 or 0.70 

If there is no printf solution, is there any other solution for this?

I do not want to use floating point.

+4
source share
3 answers

%.2d may add extra zeros

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

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

EDIT : I did not notice its UINT16 at first, as per @Eric Postpischil comment, it is better to use:

 printf("%d.%.2d", (int) (x/100), (int) (x%100)); 
+6
source
 printf("%d.%.2d", x / 100, x % 100); 
+3
source

You can use printf directly without using float

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

% 02d means zero-right justification.

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

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

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

Source: https://habr.com/ru/post/1499141/


All Articles