1

I tried many sed/awk/tail/cut/expr commands/functions but I couldn't get it.

I need to round any number I am having in a variable to the next/nearest 10th equivalent.

Example(S) on what I need to round:

Source no  >  Rounded to
1.74       > 1.80
11.74      > 11.80    
222.74     > 222.80    
5.35       > 5.40    
44.11      > 44.20    
4.93       > 5.00    
4.89       > 4.90    
4.80       > 4.90

So I need to reach the next 0.10 number !

  • The rounded number should be *.XX
  • The second X must be 0
  • The first X must be (the old number + 1)
  • The first X if -eq 9 then * should rounded up .. etc ..

What I need is rounding up my number to the next (1/10=0.10), hence 5.98 will be 6.00

The needed output format should be *.XX and the input number is also *.XX

Aserre
  • 4,916
  • 5
  • 33
  • 56
mshafey
  • 89
  • 1
  • 9

2 Answers2

0

Note that bash only supports integers.

In your case, if you only have 2 digit precision, then you need to add 0.09.

You can use bc to perform floating point operations or you can emulate the FP numbers with 2 ints:

# Pseudocode

# 11.74 (assuming we only have 2 digits precision)
A_INT=11
A_DEC=74

A_DEC_ROUND=$A_DEC+9
if A_DEC_ROUND > 100; then
    A_INT=$A_INT+1
    A_DEC_ROUND=$A_DEC_ROUND-100
fi
A_DEC_ROUND=$A_DEC_ROUND/10
A_DEC=$A_DEC_ROUND*10
Community
  • 1
  • 1
Laur Ivan
  • 4,117
  • 3
  • 38
  • 62
0

I coded what I needed and it is working just perfect ...

number=$1

INT=`echo $number|cut -f1 -d"."`

DEC=`echo $number|cut -f2 -d"."|cut -c0-1`

if [ $DEC -ne 9 ]

then

DEC=`echo $DEC+1|bc`

DEC=`echo $DEC'0'`

INT=$INT

else

DEC=00

INT=`echo $INT+1|bc`

fi

echo $INT.$DEC
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
mshafey
  • 89
  • 1
  • 9