Last active
November 22, 2021 17:12
-
-
Save o0-o/3b3249dfbedb8a47b907d637980822a2 to your computer and use it in GitHub Desktop.
[Round Number] Prints integer with rounding #Shell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# math_round.sh | |
# | |
# parameter: number (float) | |
# example: 3.14 | |
( echo "$1" | | |
awk '{ | |
x=$1 | |
ival = int(x) # integer part, int() truncates | |
# see if fractional part | |
if (ival == x) # no fraction | |
print ival # ensure no decimals | |
else { | |
if (x < 0) { | |
aval = -x # absolute value | |
ival = int(aval) | |
fraction = aval - ival | |
if (fraction >= .5) | |
print int(x) - 1 # -2.5 --> -3 | |
else | |
print int(x) # -2.3 --> -2 | |
} else { | |
fraction = x - ival | |
if (fraction >= .5) | |
print ival + 1 | |
else | |
print ival | |
} | |
} | |
}' | |
) 2>/dev/null || | |
exit 1 #failure | |
exit 0 #success | |
# https://www.gnu.org/software/gawk/manual/html_node/Round-Function.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment