Bash 将小数乘以整数

发布于 2024-09-10 14:24:02 字数 209 浏览 2 评论 0原文

我从用户输入中读取价格。当我像这样将输入乘以 int 时

T="$((价格*数量))"|bc;给出 第 272 行:12.00:语法错误:算术运算符无效(错误标记为“.00”) 或 .50

具体取决于用户输入。如何将这两个变量相乘并得到小数点后两位的总数?

I read price from user input. When i multiply the input with int like this

T="$((PRICE*QTY))"|bc; gives
line 272: 12.00: syntax error: invalid arithmetic operator (error token is ".00")
or .50

depending on user input. How do i multiply these two variables and get a total with 2 decimal points?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

演出会有结束 2024-09-17 14:24:02

这有效:


PRICE=1.1
QTY=21
RES=$(echo "scale=4; $PRICE*$QTY" | bc)
echo $RES

this works:


PRICE=1.1
QTY=21
RES=$(echo "scale=4; $PRICE*$QTY" | bc)
echo $RES
隱形的亼 2024-09-17 14:24:02
var=$(echo "scale=2;$PRICE*$QTY" |bc)

您还可以使用 awk

awk -vp=$PRICE -vq=$QTY 'BEGIN{printf "%.2f" ,p * q}'
var=$(echo "scale=2;$PRICE*$QTY" |bc)

You can also use awk

awk -vp=$PRICE -vq=$QTY 'BEGIN{printf "%.2f" ,p * q}'
诺曦 2024-09-17 14:24:02
T="$(echo "$PRICE*$QTY" | bc)"
T="$(echo "$PRICE*$QTY" | bc)"
白色秋天 2024-09-17 14:24:02

您可以使用
乘数=0.8
经验=200
texp=awk -vp=$mul -vq=$exp 'BEGIN{printf "%.2f" ,p * q}'

希望这会起作用。

You can use
mul=0.8
exp=200
texp=awk -vp=$mul -vq=$exp 'BEGIN{printf "%.2f" ,p * q}'

Hope this is going to work.

梦过后 2024-09-17 14:24:02

首先,尝试在不使用 -l 标志的情况下使用 bc(1) 进行浮点算术必然会给您一些有趣的答案:

sarnold@haig:~$ bc -q
3.5 * 3.5
12.2
sarnold@haig:~$ bc -q -l
3.5 * 3.5
12.25

其次,$ ((...)) 是尝试在 shell 中进行算术运算;我的 bash 和 dash 都无法处理浮点数。

如果您想在 shell 中进行算术运算,请注意 printf(1) 以及(可能)您 shell 的内置 printf 函数。如果您想在 bc 中进行算术运算,请注意特殊变量 scale

First, trying to do floating-point arithmetic with bc(1) without using the -l flag is bound to give you some funny answers:

sarnold@haig:~$ bc -q
3.5 * 3.5
12.2
sarnold@haig:~$ bc -q -l
3.5 * 3.5
12.25

Second, the $((...)) is an attempt to do arithmetic in your shell; neither my bash nor dash can handle floating point numbers.

If you want to do the arithmetic in your shell, note printf(1) as well as (probably) your shell's built-in printf function. If you want to do the arithmetic in bc, note the special variable scale.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文