How do I truncate a floating point number using bc
e.g if I do
echo '4.2-1.3' | bc
which outputs 2.9
how I get it to truncate/use floor to get 2
Use /
operator.
echo '(4.2-1.3) / 1' | bc
Dividing by 1 works ok if scale
is 0 (eg, if you start bc with bc
and don't change scale
) but fails if scale
is positive (eg, if you start bc with bc -l
or increase scale
). (See transcript below.) For a general solution, use a trunc
function like the following:define trunc(x) { auto s; s=scale; scale=0; x=x/1; scale=s; return x }
Transcript that illustrates how divide by 1 by itself fails in the bc -l
case, but how trunc
function works ok at truncating toward zero:
> bc -l bc 1.06.95 [etc...] for (x=-4; x<4; x+=l(2)) { print x,"\t",x/1,"\n"} -4 -4.00000000000000000000 -3.30685281944005469059 -3.30685281944005469059 -2.61370563888010938118 -2.61370563888010938118 -1.92055845832016407177 -1.92055845832016407177 -1.22741127776021876236 -1.22741127776021876236 -.53426409720027345295 -.53426409720027345295 .15888308335967185646 .15888308335967185646 .85203026391961716587 .85203026391961716587 1.54517744447956247528 1.54517744447956247528 2.23832462503950778469 2.23832462503950778469 2.93147180559945309410 2.93147180559945309410 3.62461898615939840351 3.62461898615939840351 define trunc(x) { auto s; s=scale; scale=0; x=x/1; scale=s; return x } for (x=-4; x<4; x+=l(2)) { print x,"\t",trunc(x),"\n"} -4 -4 -3.30685281944005469059 -3 -2.61370563888010938118 -2 -1.92055845832016407177 -1 -1.22741127776021876236 -1 -.53426409720027345295 0 .15888308335967185646 0 .85203026391961716587 0 1.54517744447956247528 1 2.23832462503950778469 2 2.93147180559945309410 2 3.62461898615939840351 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With