Search code examples
bashscientific-notation

Convert scientific notation number Xe+N to an integer in bash script


Given:

#!/bin/bash

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

I would like to convert this scientifically written notation number to an integer in my bash script. Right now, I use the following approach using Python within the Bash script to do it:

# 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

Is there a direct solution within bash script which I could use?

$ echo "$BASH_VERSION"
5.1.16(1)-release

And my Linux OS:

$ cat /etc/os-release
PRETTY_NAME="Ubuntu 22.04.3 LTS"
NAME="Ubuntu"
VERSION_ID="22.04"
VERSION="22.04.3 LTS (Jammy Jellyfish)"
VERSION_CODENAME=jammy
ID=ubuntu
ID_LIKE=debian
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
UBUNTU_CODENAME=jammy

UPDATE:

As an alternative given in an accepted answer, I can do the following as well to save it into a variable my_integer:

my_integer=$(awk -v x="$my_number" 'BEGIN {printf("%d\n",x)}')
echo "my_integer: $my_integer" # 2200000

Solution

  • You can also use awk that would start faster than python:

    awk -v x="$my_number" 'BEGIN {printf("%d\n",x)}'