Itai Ganot
Itai Ganot

Reputation: 6305

How can I convert from a decimal to an integral numeric variable in a bash script?

I have a value which looks like this: 26.3

I want to work on that value but I need it to be integer, so is there a simple way to do that?

26.3 -> 26
44.9 -> 44

Thanks

Upvotes: 0

Views: 6347

Answers (4)

chepner
chepner

Reputation: 531095

You appear to just want to drop the fractional part:

x=26.3
x=${x%.*}

This is handled in the shell without needing to run any external programs.

Upvotes: 0

Tom Fenech
Tom Fenech

Reputation: 74605

One option is to use awk:

$ var=26.3
$ awk -v v="$var" 'BEGIN{printf "%d", v}'
26

The %d format specifier results in only the integer part of the number being printed, rounding it down.

As Mark has mentioned in his answer, a simple substitution will fail in cases where there is no leading digit, such as .9, whereas this approach will print 0.

Rather than using a format specifier, it is also possible to use the int function in awk. The variable can be passed in on standard input rather than defining a variable to make things shorter:

$ awk '{$0=int($0)}1' <<< "44.9"
44

In case you're not familiar with awk, the 1 at the end is common shorthand, which always evaluates to true so awk performs the default action, which is to print the line. $0 is a variable which refers to the contents of the line.

Thanks to Jidder for the suggestion.

Upvotes: 2

anubhava
anubhava

Reputation: 785108

Here is a version using bc to do the ceiling to previous int:

n='26.3'
bc <<< "$n/1"
26

n='26.6'
bc <<< "$n/1"
26

Upvotes: 1

Mark Setchell
Mark Setchell

Reputation: 207455

You can use a substitution to replace a dot and anything following it:

v=26.3
s=${v/\.*/}
echo $s
26

It truncates rather than deciding which direction to round... it might have fun with .63 though :-( whereas 0.63 will be fine.

Upvotes: 2

Related Questions