Skip to content

Commit a75c65d

Browse files
committed
fix: math.sh with fallback if no awk nor bc available
1 parent b0de5a6 commit a75c65d

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

src/math.sh

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,20 @@
11
#!/usr/bin/env bash
2+
# shellcheck disable=SC2155
23

34
function math::calculate() {
45
if dependencies::has_bc; then
56
echo "$*" | bc
67
elif [[ "$*" == *.* ]] && dependencies::has_awk; then
7-
# Use awk for floating point calculations when bc is unavailable
88
awk "BEGIN { print ($*) }"
9+
elif [[ "$*" == *.* ]]; then
10+
# Strip decimal parts and leading zeros
11+
local expression=$(echo "$*" | sed -E 's/([0-9]+)\.[0-9]+/\1/g' | sed -E 's/\b0*([1-9][0-9]*)/\1/g')
12+
local result=$(( expression ))
13+
echo "$result"
914
else
10-
# Fallback to shell arithmetic which has good integer precision
11-
local result=$(( $* ))
15+
# Strip leading zeros even for purely integer math
16+
local expression=$(echo "$*" | sed -E 's/\b0*([1-9][0-9]*)/\1/g')
17+
local result=$(( expression ))
1218
echo "$result"
1319
fi
1420
}

0 commit comments

Comments
 (0)