0

I have a input file with set of float numbers like 2.45, 3.56, 54,64and so on. I need to sum them.

After reading the this article I understand that there is no straight way to do that. I can't round any numbers.

I remember that there are a way to convert in to int without rounding. Like 2.54 * 100 = 254. After that I can do all math and return it to float view using AWK.

I was trying to use bc tool, but it wont work this way.

Like, (wrong code)

a=2.54 
c=$((a * 100)) | bc -l 

Please, suggest

Not duplicate, because: I'm asking and looking to convert floating point numbers to integers, not to compare 2 floating numbers. I need to SUM it, and it is different from comparison. Besides, that question doesn't answer on my question. Point of asking here is to get closest possible answer for particular question.

Community
  • 1
  • 1
Jhonny S
  • 7
  • 2
  • The `bc` command would be more like `bc -l <<<"2.56 * 100"` than what you gave in your question (which does math in bash natively, not in bc). – Charles Duffy Feb 10 '15 at 21:59
  • ...or, to just do the math in bc: `bc -l <<<"2.56 + 3.41"` – Charles Duffy Feb 10 '15 at 22:00
  • ...as such, the question being marked duplicate is not outrageous on its face, since it's a fairly-obvious one-character change (`>` to `+`) to get from the answer given there to the correct one, without even bothering with the multiply-by-100 workaround. – Charles Duffy Feb 10 '15 at 22:01
  • Maybe a better original for this duplicate: [Floating-point arithmetic in UNIX shell script](http://stackoverflow.com/q/14222250/2157640) – Palec Feb 10 '15 at 23:44

1 Answers1

0

You could use awk,

$ echo '2.45, 3.56, 54,64' | awk -v FS=" *, *" '{for(i=1;i<=NF;i++){count = count+$i}}END{print count}'
124.01
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274