How to round or convert a float value to int with bc? getting: "(standard_in) 1: syntax error"

43,359

Solution 1

You can use printf for rounding:

$ printf "%.0f" 2743410360.320

Solution 2

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.

Solution 3

$ p=2743410360.320
$ echo $p
2743410360.320
$ echo ${p%%.*}
2743410360
Share:
43,359

Related videos on Youtube

vin
Author by

vin

Updated on September 18, 2022

Comments

  • vin
    vin almost 2 years

    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

    • Admin
      Admin over 10 years
      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
    manatwork over 10 years
    The +0.5 in the original code looks like rounding is needed.
  • Gilles 'SO- stop being evil'
    Gilles 'SO- stop being evil' over 10 years
    @manatwork Works for me with bash 4.1.5 on Debian squeeze and even bash 3.2.39 on Ubuntu 8.04.
  • manatwork
    manatwork over 10 years
    Indeed. Works fine in bash 4.2. Or maybe the problem was not the version – the first try was on Cygwin.
  • vin
    vin over 10 years
    I tried it is not working fine when i am passing a value $ printf "%.0f" $gb
  • Flimzy
    Flimzy over 9 years
    @manatwork: Are you using %i or %.0f? The former says 'invalid number' for me, the latter works.
  • manatwork
    manatwork over 9 years
    @Flimzy, I am quite (though not 100%) sure it was %.0f. My bad, I not specified the patch level of the version. It works fine in bash 4.1.5, the oldest I currently have.
  • Inetquestion
    Inetquestion almost 3 years
    5.9 rounded is not 5 This doesn't round at all. Its chopping off everything after the decimal.