将浮点数转换为整数而不用bash中的舍入 [英] Convert floating point numbers to integer without rounding in bash

查看:160
本文介绍了将浮点数转换为整数而不用bash中的舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一组浮点数的输入文件,如 2.45,3.56,54,44 等等。我需要总结一下。

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.

我记得有一种方法可以转换为int而不进行舍入。像2.54 * 100 = 254.之后,我可以做所有的数学运算并使用AWK将其返回浮动视图。

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.

我试图使用bc工具,但它不会这样工作。

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

喜欢,(错误代码)

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

请建议

不重复,因为:
我要求并希望将浮点数转换为整数,而不是比较2个浮点数。我需要对它进行总结,它与对比不同。此外,这个问题没有回答我的问题。
这里要问的是获得特定问题的最接近答案。

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.

推荐答案

你可以使用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

这篇关于将浮点数转换为整数而不用bash中的舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆