0

I want to add two number in Linux, number contains leading zeros, e.g.:

000 + 1 = 001,
111 + 4 = 115
terdon
  • 234,489
  • 66
  • 447
  • 667
Sanjay
  • 45
  • 1
  • 1
  • 5

2 Answers2

2

There may be a tool that can do this natively but I was able to accomplish it with the following function:

math_func () {
    local _n1=$1
    local _op=$2
    local _n2=$3
    local _p
    local _a
    if [ "${#_n1}" -gt "${#_n2}" ]; then
        _p=${#_n1}
    else
        _p=${#_n2}
    fi
    _a=$(echo "scale=0; $_n1 $_op $_n2" | bc -l)
    printf "%0${_p}d\n" "$_a"
}

This can also do subtraction, multiplication, and division (although you must escape the multiplication operator and it will not handle floats).

It will check the length of both input numbers and whichever is larger will be used to set the zero padding size of the output.

You call it like the following:

$ math_func 000 + 1
001
$ math_func 000000500 \* 5
000002500
$ math_func 010 / 2
005
$ math_func 2 - 1
1
jesse_b
  • 35,934
  • 12
  • 91
  • 140
2

Well I am assuming few things, but question did not mention any conditions as well!

If you know which numbers you want to add in advance, you can use simple solution like this,

need to pass numbers to add as an argument.

Certainly not optimum but just a thought!

#!/bin/bash
num1=$1
num2=$2
temp=$(( $num1 + $num2 ))
sum=$(printf "%03d" ${temp})
echo "Sum is: $sum"

Output Sum is: 001

HarshaD
  • 356
  • 1
  • 3
  • 9
  • I don't think that this is a good response because your starting numbers don't have leading zeros, then you sum them and add zeros to the sum. But if you just take a look at what the OP wrote in his example, it's obvious that he wants to sum one number that has leading zeros with another that doesn't have them, and to make the sum have leading zeros. – J. Doe May 27 '22 at 10:54