Bash无法输出Decimal值?求表达式精确到3位小数的解决方法
Hey there! The issue with your current script is that the let command only handles integer arithmetic—it truncates all decimal results to whole numbers, which is why you're getting 17.000000 instead of the expected 17.929. Let's fix that with tools that support floating-point calculations.
Why Your Current Code Fails
When you run let a=num with your input 5+50*3/20 + (19*2)/7, here's what happens under the hood:
50*3/20becomes150/20 = 7(integer division truncates 7.5 to 7)(19*2)/7becomes38/7 = 5(truncates ~5.4286 to 5)- Total:
5 + 7 + 5 = 17
No wonder the output is a whole number!
Solution 1: Use bc for Precise Floating-Point Math
bc is a command-line calculator built for arbitrary-precision arithmetic. We'll set a higher internal precision to avoid truncation errors, then format the final result to 3 decimal places (with proper rounding):
echo -e "Enter expression to calculate : \c" read expr # Calculate with 10 decimal places internally, then round to 3 result=$(echo "scale=10; $expr" | bc -l) printf '%.3f\n' "$result"
scale=10ensures we don't lose precision during intermediate calculationsbc -lloads the math library for better floating-point supportprintf '%.3f'automatically rounds the result to 3 decimal places
For your input, this will output 17.929 as expected.
Solution 2: Use awk for Simpler Floating-Point Handling
awk natively supports floating-point arithmetic, so you can compute and format the result in one clean step:
echo -e "Enter expression to calculate : \c" read expr awk "BEGIN {printf \"%.3f\n\", $expr}"
The BEGIN block runs before processing any input, directly evaluating your expression and printing it rounded to 3 decimal places. This is a concise alternative if you don't need the fine-grained control of bc.
Testing the Fixes
If you run either script and input 5+50*3/20 + (19*2)/7, you'll get the desired output:
17.929
内容的提问来源于stack exchange,提问作者Vijay

