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?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Strobe_
  • 435
  • 3
  • 5
  • 10

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
  • 57,448
  • 9
  • 113
  • 229