bc
bc is a language that supports arbitrary precision numbers with interactive execution of statements. There are some similarities in the syntax to the C programming language. A standard math library is available by command line option. If requested, the math library is defined before processing any files.[1]
- bc [EN] @ Fedora Package
- bc [EN] @ Homebrew Formula
Documentation
- man 1 'bc' [EN]
Syntax
bc [PARAMETER ...] [FILE ...]
Parameters
- -l, --mathlib
- Define the standard math library.
Examples
- int()[2]
Integer part of a float number
bc -l << EOS
define int(x) {
s = scale; scale = 0; x /= 1; scale = s; return x
}
x = 2.25; int(x)
x = -2.25; int(x)
EOS
Output:
2
-2
- ceiling()[2]
bc -l << EOS
define int(x) {
s = scale; scale = 0; x /= 1; scale = s; return x
}
define ceiling(x) {
auto r; r = int(x); if (r < x) r += 1; return r
}
x = 2.25; ceiling(x)
x = -2.25; ceiling(x)
EOS
Output:
3
-2
- floor()[2]
bc -l << EOS
define int(x) {
s = scale; scale = 0; x /= 1; scale = s; return x
}
define ceiling(x) {
auto r; r = int(x); if (r < x) r += 1; return r
}
define floor(x) {
return -ceiling(-x)
}
x = 2.25; floor(x)
x = -2.25; floor(x)
EOS
Output:
2
-3
- round()[2]
bc -l << EOS
define int(x) {
s = scale; scale = 0; x /= 1; scale = s; return x
}
define round(x) {
if (x < 0) x -= 0.5 else x += 0.5; return int(x)
}
x = 2.25; round(x)
x = -2.25; round(x)
x = 2.75; round(x)
x = -2.75; round(x)
EOS
Output:
2
-2
3
-3
- round_to()[2]
bc -l << EOS
define int(x) {
s = scale; scale = 0; x /= 1; scale = s; return x
}
define round(x) {
if (x < 0) x -= 0.5 else x += 0.5; return int(x)
}
define round_to(x,y) {
return y * round(x / y)
}
y = 250 /* Round to 250 */
x = 1122; round_to(x, y)
x = 1144; round_to(x, y)
y = 0.05 /* Round to 0.05 */
x = 2.22; round_to(x, y)
x = 2.23; round_to(x, y)
EOS
Output:
1000
1250
2.20
2.25