Skip to content

Instantly share code, notes, and snippets.

@koyudoon
Last active August 29, 2015 14:06
Show Gist options
  • Save koyudoon/ee80adb0b8249c6a3c3f to your computer and use it in GitHub Desktop.
Save koyudoon/ee80adb0b8249c6a3c3f to your computer and use it in GitHub Desktop.
Round off the decimal value in GNU bc
#! /usr/bin/bc
# UUID: 3bf231de-04dc-4c02-92f4-20b891a6f50d
# based on: http://gauc.no-ip.org/awk-users-jp/blis.cgi/DoukakuAWK_294
define decimal_round(num, decimal_pos) {
if ( decimal_pos <= 0 ) halt
decimal_pos = decimal_pos - 1
scale = decimal_pos
if (num >= 0) {
num = (num * 10 ^ decimal_pos + 0.5) / (10 ^ decimal_pos)
} else {
num = (num * 10 ^ decimal_pos - 0.5) / (10 ^ decimal_pos)
}
return num
}
# e.g.
print decimal_round(0.8955, 2), "\n" # .9
print decimal_round(0.8955, 4), "\n" # .896
print decimal_round(-0.8955, 3), "\n" # -.90
print decimal_round(-0.8955, 1), "\n" # -1
quit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment