Hey everyone, I was wondering if i am able to write a sed command to round a number to two decimal places. So for example:
1.58674
would be
1.58
I just want to chop off the numbers to the right of the second digit after the period. I know this is probably trivial but the closest i got was
sed 's/[.].*$//'
which deletes everything after the period including the period. Thanks.
CarloM
2
sed 's/\(\.[0-9][0-9]\).*$/\1/g'
EDIT: Missed a backslash
1 Like
but not in sed ..
$ echo "scale=2;1.58674/1" | bc
1.58
I tried this value "test.test1234" with send command not working.
The above sed code is for numbers... notice [0-9]?...
Following code will give you test.te as output
echo test.test1234| sed 's/\(\...\).*$/\1/g'
--ahamed
i want only number values,not character...
echo test.test1234 | sed 's/[^0-9]*//g'
--ahamed
FWIW -
1.58641 rounded to 2 decimals is 1.59, truncated to 2 decimals is 1.58
Rounding with the printf command
a=1.58674
rnd_a=$( printf "%.2f" $a)
The examples shown so far truncate.