0

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

pstanton
  • 35,033
  • 24
  • 126
  • 168
Itai Ganot
  • 5,873
  • 18
  • 56
  • 99
  • At least write the reason for voting down... – Itai Ganot Dec 08 '14 at 11:29
  • 1
    possible duplicate of [How to round float in Bash? (to a decimal)](http://stackoverflow.com/questions/23389258/how-to-round-float-in-bash-to-a-decimal). Check also [rounding up float in bash to a decimal](http://stackoverflow.com/questions/26465496/rounding-up-float-point-numbers-bash) and [how to round floating point numbers in shell](http://unix.stackexchange.com/questions/167058/how-to-round-floating-point-numbers-in-shell) – fredtantini Dec 08 '14 at 11:30
  • you are 'flooring' ie always rounding down. – pstanton Oct 07 '16 at 05:20

4 Answers4

2

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.

Community
  • 1
  • 1
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • 1
    Other ways, `awk '$0=int($0)' <<< "26.3"` or if it can be 0, `'{$0=int($0)}1'` or using a variable `awk -v v="$var" 'BEGIN{print int(v)}'` –  Dec 08 '14 at 11:52
2

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.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
1

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

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.

chepner
  • 497,756
  • 71
  • 530
  • 681