Rounding number, but....

Dear Experts,

I'm trying to find a way to round a number but in this way:

14367.577 ---> 14000

I used the following to round the number to the closer integer:

echo $var|awk '{print int($1+0.5)}' 

and also:

xargs printf "%1.0f"

However, they don't work for my above example.

Please, any hints and support will be very grateful.

Best regards,

Try:

echo $var|awk '{x=int($1+0.5);sub("...$","000",x);print x}'
num=14367.577
printf "%2.2s000\n" "$(( ${num%.*} / 1000 ))"

Dear bartus11 and Dear cfajohnson,

Many thanks for your answers, I tried both and the one that it's close to what I need is bartus11's code. However, I forgot to say that I have a range of values from 0 to 100 000. In fact, this code worked well for most of my values (and also more than 100 000), but I have problems in the range between 99.5 and 999.4. For example, if I run the code with:

var=99.4
echo $var|awk '{x=int($1+0.5);sub("...$","000",x);print x}'

then I get 99, which is very good.

However, from 99.5 to 999.4, I get 000. In this case, for instance, I expect to have with the number 459.3244, just 450.

In the case this code coulnd't be modified to cover the whole range (from 0 to 100 000), how could the script be modified to cover the range from 99.5 to 999.4?

I'm very grateful for your excellent support, many thanks again,

Best regards,

Please document the rules, and provide some examples.
Your initial question looks to round to the nearest 1000.

This requires bash or ksh93:

#!/bin/bash
var=${1:-12345.6789}
num=${var%.*}
pad=$(( ${#num} - 2 ))
sig=${num:0:2}
printf "%d%0${pad}d\n" "$sig" 0

Thank you for your answers and sorry for confusing you.

This is what I have for example:

15.657
47.234
178.99
472.88
982.45
3762.99
5933.21
9925.43
18772.22
53827.32
82611.21
104321.12

and this is what I need as output:

20
50
200
 500
 1000
 4000
 6000
 10000
 20000
 50000
 80000
 100000
 

Sorry again for confusing you, it's been a long day...

Thank you,

 echo $var| awk '{x=10**(length(int($1))-1);print x*int(($1/x)+0.5)}'
 
$ cat tst
15.657
47.234
178.99
472.88
982.45
3762.99
5933.21
9925.43
18772.22
53827.32
82611.21
104321.12
$ awk '{x=10**(length(int($1))-1);print x*int(($1/x)+0.5)}' tst
20
50
200
500
1000
4000
6000
10000
20000
50000
80000
100000

Thank you so much ctsgnb, it works perfectly, thank you to all!!!

#!/bin/ksh93

while read x
do
    y=$(( int(x) )); y=$(( 10 ** (( ${#y} - 1 )) ))
    print $(( y * int((x/y)+0.5) ))
done < infile