Rounding up float point numbers bash

房东的猫 提交于 2020-01-03 06:48:11

问题


Ok, so I'm trying to round up an input of 17.92857, so that it gets an input of 17.929 in bash.

My code so far is:

read input
echo "scale = 3; $input" | bc -l

However, when I use this, it doesn't round up, it returns 17.928.

Does anyone know any solutions to this?


回答1:


In case input contains a number, there is no need for an external command like bc. You can just use printf:

printf "%.3f\n" "$input"

Edit: In case the input is a formula, you should however use bc as in one of the following commands:

printf "%.3f\n" $(bc -l <<< "$input")
printf "%.3f\n" $(echo "$input" | bc -l)



回答2:


To extend Tim's answer, you can write a shell helper function round ${FLOAT} ${PRECISION} for this:

#!/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



回答3:


A little trick is to add 0.0005 to your input, this way you will have your number round up correctly.




回答4:


if you're receiving the round-off error with the number 17.928 try this: read y v=echo "scale = 3; $y" |bc -l if [ $v == 17.928 ] ; then echo "17.929" else echo $v fi



来源:https://stackoverflow.com/questions/26465496/rounding-up-float-point-numbers-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!