一、现象
$ echo "0.56" | awk '{printf "%d\n",$1*100}' # 56 打印正确
$ echo "0.57" | awk '{printf "%d\n",$1*100}' # 56 打印不正确
$ echo "0.58" | awk '{printf "%d\n",$1*100}' # 57 打印不正确
$ echo "0.59" | awk '{printf "%d\n",$1*100}' # 59 打印正确
二、原因
因为使用浮点数无法准确表示小数
# echo "0.55" | awk '{printf "%2.20f\n",$1*100}'
55.00000000000000710543
# echo "0.56" | awk '{printf "%2.20f\n",$1*100}'
56.00000000000000710543
# echo "0.57" | awk '{printf "%2.20f\n",$1*100}'
56.99999999999999289457
# echo "0.58" | awk '{printf "%2.20f\n",$1*100}'
57.99999999999999289457
# echo "0.59" | awk '{printf "%2.20f\n",$1*100}'
59.00000000000000000000
三、解决方法
# echo "0.56" | awk '{printf "%2.0f\n",$1*100}'
56
# echo "0.57" | awk '{printf "%2.0f\n",$1*100}'
57
# echo "0.58" | awk '{printf "%2.0f\n",$1*100}'
58
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/20750200/viewspace-693989/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/20750200/viewspace-693989/