skip to Main Content

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("%dn",x)}')
echo "my_integer: $my_integer" # 2200000

2

Answers


  1. Just use printf(1) with an appropriate floating point conversion to not print anything after (or including) the decimal poin:

    $ printf "%.0fn" "2.2e+6"
    2200000
    

    or to save in a variable,

    printf -v my_integer "%.0f" "2.2e+6"
    
    Login or Signup to reply.
  2. You can also use awk that would start faster than python:

    awk -v x="$my_number" 'BEGIN {printf("%dn",x)}'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search