9

I will get value like 2743410360.320 and I want value like 2743410360 to a variable.

I tried

INTValueOfGB=$ echo "($gb+0.5)/1" | bc

But I am getting (standard_in) 1: syntax error

1
  • Please check that your code's syntax is still the one you intended to post after I edited it. (That solitary $ sign looks quite interesting.)
    – manatwork
    Nov 15, 2013 at 11:23

4 Answers 4

10

You can use printf for rounding:

$ printf "%.0f" 2743410360.320
6
  • 1
    In bash 4.1 the builtin printf says “invalid number”. Works fine with /usr/bin/printf.
    – manatwork
    Nov 15, 2013 at 11:39
  • @manatwork Works for me with bash 4.1.5 on Debian squeeze and even bash 3.2.39 on Ubuntu 8.04. Nov 16, 2013 at 22:18
  • Indeed. Works fine in bash 4.2. Or maybe the problem was not the version – the first try was on Cygwin.
    – manatwork
    Nov 17, 2013 at 12:36
  • I tried it is not working fine when i am passing a value $ printf "%.0f" $gb
    – vin
    Nov 18, 2013 at 5:58
  • @manatwork: Are you using %i or %.0f? The former says 'invalid number' for me, the latter works.
    – Flimzy
    Mar 6, 2015 at 15:14
7

I don't see an answer to @vin's problem, which is:

But I am getting (standard_in) 1: syntax error

The bc command prints (standard_in) 1: syntax error because the shell variable gb is not set:

$ unset gb
$ echo "($gb+0.5)/1" | bc
(standard_in) 1: syntax error

$ gb=2743410360.320
$ echo "($gb+0.5)/1" | bc
2743410360

In the comments to the @dchirikov's answer, @vin says printf "%.0f" is "not working":

$ unset gb
$ printf '%.0f\n' $gb
0

$ gb=2743410360.320
$ printf '%.0f\n' $gb
2743410360

In both of the areas where @vin has problems, the unset variable reproduces the problem, and setting the variable solves the problem.

3
$ p=2743410360.320
$ echo $p
2743410360.320
$ echo ${p%%.*}
2743410360
3
  • 3
    The +0.5 in the original code looks like rounding is needed.
    – manatwork
    Nov 15, 2013 at 11:36
  • simple - effective code
    – 3kstc
    Aug 8, 2016 at 4:04
  • 1
    5.9 rounded is not 5 This doesn't round at all. Its chopping off everything after the decimal. Jul 16, 2021 at 18:14
3

Your command needs a couple of ( ):

INTValueOfGB=$( echo "($gb+0.5)/1" | bc )

But that will not round the number, for that to work you need to set scale to 0:

INTValueOfGB=$( echo "scale=0;($gb+0.5)/1" | bc )

That will round up (from x.5) to the next integer.

To get "round to next even integer" (Banker's rule), you need to use printf rounding:

LC_NUMERIC=C printf "%.0f" 2743410360.320

The LC_NUMERIC is to ensure that numbers are processed with a dot as decimal. That is not what users in Germany will like to use, this should work with decimals with ,:

$ LC_NUMERIC=de_DE.utf8 printf "%.0f" 2743410360,320
2743410360

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .