3

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?

Strobe_
  • 435

1 Answers1

7

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.

mikeserv
  • 58,310