Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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 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.

3  
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 at 18:03
    
I agree with manatwork , you need to use bc –  Renan Vicente Mar 30 at 18:07
1  
And you need to divide by 2.54² –  Stéphane Chazelas Mar 30 at 20:18
    
1 inch = 2.54cm –  Strobe_ Mar 30 at 22:04
    
@Strobe_ That is true, but one squared inch equals 2.54 squared centimeters. –  mikeserv Mar 31 at 7:16
add comment

1 Answer 1

up vote 4 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
1  
Thanks that seems to work. –  Strobe_ Mar 30 at 18:45
1  
And thank you for confirming. –  mikeserv Mar 30 at 19:04
add comment

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