How to hide or delete the zero in my bash script?

左心房为你撑大大i 提交于 2020-01-15 15:33:51

问题


This is my script:

echo -n "number 1 :";
read bil1
echo -n "number 2 :";
read bil2
multiple=$(echo $bil1*$bil2 |bc -l |sed -e 's/^\./0./' -e 's/^-\./-0./');
echo " Your result : $bil1 * $bil2 = $multiple ";

If I input 9.5 for $bil1 and 300 for $bil2, the result is 2850.0.

I want the result:

Your result : 9.5 * 300 = 2850

How do I hide or delete the zero at the end of the result? I.e. show only 2850 ?


回答1:


Add the following part to your sed command (at the end):

-e 's/\.0*$//'

(Delete a dot followed by arbitrarily many zeroes at the end by nothing.)

By the way, you better replace echo $bil1*$bil2 by echo "$bil1*$bil2", otherwise you may get strange effects depending on the contents of the current directory.




回答2:


use bash's builtin printf to control the output

$ bil1=9.5; bil2=300; printf "%.0f\n" $(bc -l <<< "$bil1 * $bil2")
2850



回答3:


Assign the normal, floating-point output of bc to the variable, then trim it using parameter expansion:

multiple=$(echo "$bil1*$bil2" | bc -l)
# Not POSIX, unfortunately
shopt -s extglob
multiple=${multiple%.+(0)}
echo " Your result : $bil1 * $bil2 = $multiple "

A POSIX solution is to let printf do the work

multiple=$(echo "$bil1*$bil2" | bc -l)
printf " Your result : %1.1f * %d = %1.0f\n" $bil1 $bil2 $multiple 


来源:https://stackoverflow.com/questions/16568824/how-to-hide-or-delete-the-zero-in-my-bash-script

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