[英]printf: how to align numbers on decimal point
考慮有一組數字:
my @array = (
1.788139343e-007, 0.0547055073198, -0.703213036125,
-0.583665880391, -1.41198285298, +0.171879081676,
-0.58966025098, -86.0627173425, -0.84449797709,
3.49876623321e-005, 3.02660429162, -0.256948695361);
我想將小數點對齊在總寬度為m的第n列(可能n = 6和m = 25)
如果使用%f
我得到了很好的對齊數字,但是需要科學記數法的數字正在被破壞。 usging %g
將點后面的precision參數解釋為絕對精度,導致小數點后面的小數點不同。 由於大多數數字在(-10,10)范圍內,我不想采用科學記數法%e
是否有我忽略的標志或格式屬性(或組合)?
預期的結果將是:
foreach my $f (@array){
printf("[%+25.12g]$/", $f);
}
[ +1.788139343e-007 ]
[ +0.0547055073198 ]
[ -0.703213036125 ]
[ -0.583665880391 ]
[ -1.41198285298 ]
[ +0.0171879081676 ]
[ -0.58966025098 ]
[ -86.0627173425 ]
[ -0.84449797709 ]
[ +3.49876623321e-005 ]
[ +3.02660429162 ]
[ -0.256948695361 ]
甚至更好
[ +1.7881393430000e-007 ]
[ +0.0547055073198 ]
[ -0.7032130361250 ]
[ -0.5836658803910 ]
[ -1.4119828529800 ]
[ +0.0171879081676 ]
[ -0.5896602509800 ]
[ -86.0627173425000 ]
[ -0.8444979770900 ]
[ +3.4987662332100e-005 ]
[ +3.0266042916200 ]
[ -0.2569486953610 ]
(問題是關於Perl但是s?printf
的格式字符串是相當獨立的,所以我也添加了C
標簽)
[*]printf
函數允許您:
因此,如果您知道點之前有多少字符( d = sprintf(buf, "%.0f", ar[i]);
),您可以使用( printf("[%*s %g", 4-d, "", ar[i]);
)。
然后使用相同的邏輯來對齊右括號:
#include <stdio.h>
int main()
{
double ar[] = {
1.788139343e-007, 0.0547055073198, -0.703213036125,
-0.583665880391, -1.41198285298, 0.171879081676,
-0.58966025098, -86.0627173425, -0.84449797709,
3.49876623321e-005, 3.02660429162, -0.256948695361};
for (int i = 0; i < 12; ++i)
{
/* buffer to count how much character are before the dot*/
char buf[64];
/* how much before the dot? */
int d = sprintf(buf, "%+.0lf", ar[i]);
/* write float with aligned dot and store second padding */
int e = printf("[%*s %+.15lg", 4-d, "", ar[i]);
printf("%*s]\n", 25-e, "");
}
return 0;
}
得到:
[ +1.788139343e-07 ]
[ +0.0547055073198 ]
[ -0.703213036125 ]
[ -0.583665880391 ]
[ -1.41198285298 ]
[ +0.171879081676 ]
[ -0.58966025098 ]
[ -86.0627173425 ]
[ -0.84449797709 ]
[ +3.49876623321e-05 ]
[ +3.02660429162 ]
[ -0.256948695361 ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.