在bash脚本中将科学计数法数字Xe+N转换为整数

问题描述 投票:0回答:2

鉴于:

#!/bin/bash

# Define the number in scientific notation
my_number="2.2e+6"

我想在 bash 脚本中将这个科学书写的符号数字转换为整数。现在,我使用以下方法在 Bash 脚本中使用 Python 来执行此操作:

# Convert scientific notation to integer using Python
my_integer=$(python -c "print(int($my_number))")

echo "Original number: $my_number"
echo "As an integer: $my_integer" 

Original number: 2.2e+6
As an integer: 2200000

bash 脚本中有我可以使用的直接解决方案吗?

bash casting scientific-notation
2个回答
0
投票

只需使用

printf(1)
进行适当的浮点转换,就不会在小数点之后(或包含小数点)打印任何内容:

$ printf "%.0f\n" "2.2e+6"
2200000

或者保存在变量中,

printf -v my_integer "%.0f" "2.2e+6"

0
投票

您还可以使用

awk
,它的启动速度比
python
更快:

awk -v x="$my_number" 'BEGIN {printf("%d\n",x)}'
© www.soinside.com 2019 - 2024. All rights reserved.