简体   繁体   English

printf,如何为整数插入小数点

[英]printf, how to insert decimal point for integer

I have an UINT16 unsigned integer of say我有一个UINT16无符号整数 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如何使用 printf 在最后两位数字前插入小数点,以便示例数字显示为

44.55, 3.12, 5.60 or 0.70

If there is no printf solution, is there another solution for this?如果没有 printf 解决方案,是否还有其他解决方案?

I do not wish to use floating point.我不想使用浮点数。

%.2d could add the extra padding zeros %.2d可以添加额外的填充零

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

For example, if n is 560 , the output is: 5.60例如,如果n560 ,则输出为: 5.60

EDIT : I didn't notice it's UINT16 at first, according to @Eric Postpischil's comment, it's better to use:编辑:根据@Eric Postpischil 的评论,我一开始没有注意到它是UINT16 ,最好使用:

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 而不使用 float

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

%02d means right align with zero padding. %02d 表示与零填充右对齐。

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.通过查看@ Eric Postpischil 的评论,最好这样使用。

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

with a int x1000 precision 1234123 -> 1234.123具有 int x1000 精度 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
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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