bash中的浮点除法 [英] Floating-point division in bash

查看:91
本文介绍了bash中的浮点除法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将用户输入的任何数字转换为2个小数位. 例如

What is the total cost in cents? 2345
output: 23.45

这是我到目前为止的代码

percentage=20 #cannot change numerical value must convert into 0.20
echo -n "What is the total cost? ";
read cost_in_cents
echo "scale 1; $cost_in_cents" | bc

我还要对百分比进行乘法运算,如何将百分比转换为浮点数(0.20)

解决方案

也许是对逆波兰表示法计算器的怀旧之情,但我在这里使用dc而不是bc:

dc <<<"2 k $cost_in_cents 100 / p"

正确地,输出是浮点数(精度的小数点后两位).

完全相同的代码,无需进行任何更改,即可将20转换为.20.


有关bash中浮点数学的完整讨论,请参见 BashFAQ#22 . /p>

I'm trying to convert whatever numbers the user inputs into 2 decimal places. For instance

What is the total cost in cents? 2345
output: 23.45

this is the code i have so far

percentage=20 #cannot change numerical value must convert into 0.20
echo -n "What is the total cost? ";
read cost_in_cents
echo "scale 1; $cost_in_cents" | bc

I'm also going to be doing some multiplication with percentage, how can i also convert the percentage into a float (0.20)

解决方案

Perhaps it's nostalgia for reverse polish notation desk calculators, but I'd use dc rather than bc here:

dc <<<"2 k $cost_in_cents 100 / p"

Output is, properly, a float (with two digits past the decimal point of precision).

The exact same code, with no changes whatsoever, will work to convert 20 to .20.


See BashFAQ #22 for a full discussion on floating-point math in bash.

这篇关于bash中的浮点除法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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