15

how to remove decimal place in shell script.i am multiplying MB with bytes to get value in bytes .I need to remove decimal place.

ex:-
196.3*1024*1024
205835468.8
expected output
205835468
1
  • What shell are you using? bash? csh? ksh? fish?
    – Shawn Chin
    Dec 2, 2011 at 13:21

2 Answers 2

32

(You did not mention what shell you're using; this answer assumes Bash).

You can remove the decimal values using ${VAR%.*}. For example:

[me@home]$ X=$(echo "196.3 * 1024 * 1024" | bc)
[me@home]$ echo $X
205835468.8
[me@home]$ echo ${X%.*}
205835468

Note that this truncates the value rather than rounds it. If you wish to round it, use printf as shown in Roman's answer.

The ${variable%pattern} syntax deletes the shortest match of pattern starting from tbe back of variable. For more information, read http://tldp.org/LDP/abs/html/string-manipulation.html

0
14

Use printf:

printf %.0f $float

This will perform rounding. So if float is 1.8, it'll give you 2.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.