四舍五入浮点数字bash
好的,我正试图将一个四舍五入浮点数字bash,bash,shell,floating-point,decimal,rounding,Bash,Shell,Floating Point,Decimal,Rounding,好的,我正试图将一个17.92857的输入四舍五入,以便它在bash中得到一个17.929的输入 到目前为止,我的代码是: read input echo "scale = 3; $input" | bc -l 但是,当我使用它时,它不会取整,而是返回17.928 有人知道这个问题的解决方法吗?如果输入包含一个数字,则不需要像bc这样的外部命令。您只需使用printf: printf "%.3f\n" "$input" 编辑:如果输入是公式,则应使用bc作为以下命令之一: printf "%
17.92857
的输入四舍五入,以便它在bash中得到一个17.929
的输入
到目前为止,我的代码是:
read input
echo "scale = 3; $input" | bc -l
但是,当我使用它时,它不会取整,而是返回17.928
有人知道这个问题的解决方法吗?如果
输入包含一个数字,则不需要像bc
这样的外部命令。您只需使用printf
:
printf "%.3f\n" "$input"
编辑:如果输入是公式,则应使用bc
作为以下命令之一:
printf "%.3f\n" $(bc -l <<< "$input")
printf "%.3f\n" $(echo "$input" | bc -l)
printf“%.3f\n”$(bc-l一个小技巧是将0.0005
添加到您的输入中,这样您可以正确地对数字进行四舍五入。如果您收到17.928的四舍五入错误,请尝试以下操作:
阅读
v=echo“scale=3;$y”| bc-l
如果[$v==17.928];则
回声“17.929”
其他的
回音$v
fi为了扩展Tim的答案,您可以为此编写一个shell帮助函数round${FLOAT}${PRECISION}
:
#!/usr/bin/env bash
round() {
printf "%.${2}f" "${1}"
}
PI=3.14159
round ${PI} 0
echo
round ${PI} 1
echo
round ${PI} 2
echo
round ${PI} 3
echo
round ${PI} 4
echo
round ${PI} 5
echo
round ${PI} 6
echo
# Outputs:
3
3.1
3.14
3.142
3.1416
3.14159
3.141590
# To store in a variable:
ROUND_PI=$(round ${PI} 3)
echo ${ROUND_PI}
# Outputs:
3.142
即使Tim在2014年已经回答了我的问题,我还是想分享Zane功能的改进版本
#!/usr/bin/env bash
# round a float number to the given decimal digits
# if $2 is not given or not a positive integer its set to zero
# float must be in international format, this is more save for scripts
# to use other format replace LC_ALL=C with your language.
_round_float() {
local digit="${2}"; [[ "${2}" =~ ^[0-9]+$ ]] || digit="0"
LC_ALL=C printf "%.${digit}f" "${1}"
}
有关如何使用该函数的一些示例:
# round pi constant
PI=3.141599236
_round_float $PI 0 3
_round_float $PI 1 3.1
_round_float $PI 3 3.142
_round_float $PI 9 3.141599236
_round_float $PI -3 3
_round_float $PI abc 3
您还可以动态调整逗号位置,即除以/乘以10
#!/bin/bash
# change metric base unit
UNIT=1234.567890
# comma 1 position right, multiply by 10
_round_float ${UNIT}e1 3 12345.678
# comma 3 positions left, eg convert milli seconds to seconds
_round_float ${UNIT}e-3 3 1.234
# comma 3 positions right, eg convert m3 to liters
_round_float ${UNIT}e3 0 1234567
您可以使用printf-v output“%.3f\n”“$input”
将printf的输出分配给变量$output。必须来自hackerrank(),或者像@Tim说的那样使用printfi如果四舍五入到三位,您实际上应该添加.0005
,而不是.005
。但是为什么不能这样做呢?但是您必须先设置一个更大的比例>3(否则0.0005=0.000),然后设置scale=3并使用,例如,x/1
计算结果。负x也可能会出现意外结果,如果(x<0){x=x-0.0005;}否则{x=x+0.0005}
或类似值,您可能需要使用。请尝试“圆形xzzzzzzzz”;-)