Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This question already has an answer here:

Basically I need to convert centimetres to inches which I am trying to do by diving the area in centimetres by 2.54.

But I just cannot get this to work.

echo "please enter width and then height"

read width
read height

area=$(($width * $height))
inchesarea=$((area / 2.54))

echo $area
echo $inchesarea

Should I be using bc for this?

share|improve this question

marked as duplicate by goldilocks, terdon, slm, jasonwryan, Stéphane Chazelas Mar 30 '14 at 20:20

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

As most of shells are limited to integer arithmetic, you have to use either bc or pick something else from How to do integer & float calculations, in bash or other languages/frameworks?. – manatwork Mar 30 '14 at 18:03
I agree with manatwork , you need to use bc – Renan Vicente Mar 30 '14 at 18:07
And you need to divide by 2.54² – Stéphane Chazelas Mar 30 '14 at 20:18
1 inch = 2.54cm – Strobe_ Mar 30 '14 at 22:04
@Strobe_ That is true, but one squared inch equals 2.54 squared centimeters. – mikeserv Mar 31 '14 at 7:16
up vote 5 down vote accepted

You might, but this is a constant, so this should work just as well:

r=$(((area*10000)/254)) ; printf %d.%d  ${r%??} ${r#${r%??}}

This presents some difficulty when you get into working with large numbers - like more than 20 digits - but for many things it's acceptable.

This will automatically restrict and round your result to two decimal places - which, after all, aren't decimal places after we multiply. We then just handle the result as a string - first removing the last two characters from the result and inserting a decimal place, then adding them on again afterward.

This should be POSIX portable.

share|improve this answer
Thanks that seems to work. – Strobe_ Mar 30 '14 at 18:45
And thank you for confirming. – mikeserv Mar 30 '14 at 19:04

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