You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash无法输出Decimal值?求表达式精确到3位小数的解决方法

Fixing Floating-Point Calculation in Your Bash Script

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/20 becomes 150/20 = 7 (integer division truncates 7.5 to 7)
  • (19*2)/7 becomes 38/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=10 ensures we don't lose precision during intermediate calculations
  • bc -l loads the math library for better floating-point support
  • printf '%.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:55:06