简体   繁体   中英

Convert floating point numbers to integer without rounding in bash

I have a input file with set of float numbers like 2.45, 3.56, 54,64 and 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM