Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bc truncate floating point number

Tags:

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

like image 437
Bilal Syed Hussain Avatar asked Dec 13 '13 03:12

Bilal Syed Hussain


2 Answers

Use / operator.

echo '(4.2-1.3) / 1' | bc 
like image 86
timrau Avatar answered Sep 21 '22 16:09

timrau


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 
like image 31
James Waldby - jwpat7 Avatar answered Sep 20 '22 16:09

James Waldby - jwpat7