MATLAB: Having trouble with the outputs giving me 4 decimal points when I only want 2

bus faredecimal placesdecimalshomework

I'm trying to answer the following homework question:
Write a function called fare that computes the bus fare one must pay in a given city based on the distance travelled. Here is how the fare is calculated: the first mile is $2. Each additional mile up to a total trip distance of 10 miles is 25 cents. Each additional mile over 10 miles is 10 cents. Miles are rounded to the nearest integer other than the first mile which must be paid in full once a journey begins. Children 18 or younger and seniors 60 or older get a 20% discount. The inputs to the function are the distance of the journey and the age of the passenger in this order. Return the fare in dollars, e.g., 2.75 would be the result returned for a 4-mile trip with no discount.
And this is my attempt(where d= distance, a=age):
function cost= fare(d, a)
flat_rate= 2;
if (0<=d) && (d<=10) && (18<a) && (a<60)
output= flat_rate + (.25*(round(d)-1))
elseif d>10 && (18<a) && (a<60)
output= flat_rate + (.25*9)+ (.10*(round(d)-10))
elseif (0<=d) && (d<=10) && (18>a || 60<a)
output= (flat_rate + (.25*(round(d)-1)))*(.80)
elseif d>10 && (18>a || 60<a)
output= flat_rate + (.25*9)+ (.10*(round(d)-10))*(.80)
end
I've been trying to test out some values, and the first one I tried was setting d=4, a=44, which should give the expected output of 2.75. However, my output gives me 2.7500. What could I do to fix my outputs to only two decimal points?
Thanks 🙂

Best Answer

Type
format bank
And then everything will be printed to two-decimal precision until you restart Matlab. Formatting styles are described here.