[英]printf, how to insert decimal point for integer
我有一個UINT16
無符號整數 say
4455, 312, 560 or 70.
如何使用 printf 在最后兩位數字前插入小數點,以便示例數字顯示為
44.55, 3.12, 5.60 or 0.70
如果沒有 printf 解決方案,是否還有其他解決方案?
我不想使用浮點數。
%.2d
可以添加額外的填充零
printf("%d.%.2d", n / 100, n % 100);
例如,如果n
為560
,則輸出為: 5.60
編輯:根據@Eric Postpischil 的評論,我一開始沒有注意到它是UINT16
,最好使用:
printf("%d.%.2d", (int) (x/100), (int) (x%100));
printf("%d.%.2d", x / 100, x % 100);
您可以直接使用printf 而不使用 float
printf("%d.%02d", num/100, num%100);
%02d 表示與零填充右對齊。
if num is 4455 ==>output is 44.55
if num is 203 ==>output is 2.03
編輯:
通過查看@ Eric Postpischil 的評論,最好這樣使用。
printf("%d.%02d", (int) (num/100), (int) (num%100));
具有 int x1000 精度 1234123 -> 1234.123
printf("%4d.%.3d\n", x / 1000, x % 1000);
如果您需要四舍五入到小數點后兩位
printf("%4d.%.2d\n", ((x+5)/10) / 100, ((x+5)/10) % 100);
僅測試呈陽性
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.