Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove decimal from a variable?

Tags:

shell

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
like image 618
RanjitRock Avatar asked Dec 02 '11 13:12

RanjitRock


People also ask

How do you remove a decimal value?

Step 1: Write down the decimal divided by 1. Step 2: Multiply both top and bottom by 10 for every number after the decimal point. (For example, if there are two numbers after the decimal point, then use 100, if there are three then use 1000, etc.) Step 3: Simplify (or reduce) the Rational number.

How do you remove a decimal in Python?

To remove the decimal from a number, we can use the int() method in Python. The int() method takes the number as an argument and returns the integer by removing the decimal part from it. It can be also used with negative numbers.

How do you get rid of decimals in C++?

Simply, the trunc() function truncate the value after decimal and returns the integer part only.


2 Answers

(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

like image 66
Shawn Chin Avatar answered Nov 05 '22 02:11

Shawn Chin


Use printf:

printf %.0f $float

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

like image 28
Roman Byshko Avatar answered Nov 05 '22 01:11

Roman Byshko