Present the Result
By the end of this lesson, you'll be able to:
- Format a Decimal result into a clean, readable String
- Combine all four lessons into one finished Calculator class
- Recognize that presentation is part of a program's job, not an afterthought
Prerequisites: "Handle Invalid Input"
Formatting the output
Decimal result = 17.5;
String formatted = String.valueOf(result.setScale(2));
System.debug(formatted); // "17.50"
setScale(2) rounds and pads a Decimal to exactly 2 decimal places — the difference between a calculator that prints 17.5 versus one that consistently prints 17.50, which matters for anything involving money.
Building a full summary message
Decimal a = 12;
Decimal b = 5;
String operatorSymbol = '+';
Decimal result = a + b;
String summary = a + ' ' + operatorSymbol + ' ' + b + ' = ' + result.setScale(2);
System.debug(summary); // "12 + 5 = 17.00"
This is String concatenation from Module 4, combined with setScale — turning a raw number into a message a user could actually read and understand at a glance.
The complete Calculator class
public class Calculator {
public String calculateAndFormat(Decimal a, Decimal b, String operatorSymbol) {
Decimal result;
switch on operatorSymbol {
when '+' {
result = a + b;
}
when '-' {
result = a - b;
}
when '*' {
result = a * b;
}
when '/' {
if (b == 0) {
return 'Error: cannot divide by zero.';
}
result = a / b;
}
when else {
return 'Error: unrecognized operator "' + operatorSymbol + '".';
}
}
return a + ' ' + operatorSymbol + ' ' + b + ' = ' + result.setScale(2);
}
}
Every piece from this module is here: the planned structure (Lesson 1), the switch-based operations (Lesson 2), the division-by-zero and unrecognized-operator guards (Lesson 3), and clean formatted output (this lesson) — one small, complete, safe program.
Using the finished calculator
Calculator calc = new Calculator();
System.debug(calc.calculateAndFormat(12, 5, '+')); // "12 + 5 = 17.00"
System.debug(calc.calculateAndFormat(10, 0, '/')); // "Error: cannot divide by zero."
System.debug(calc.calculateAndFormat(9, 3, '?')); // "Error: unrecognized operator "?"."
Three calls exercising the happy path, the division-by-zero guard, and the unrecognized-operator guard — all handled cleanly by the one finished method.
Exercise
Given Decimal price = 49.5, write code that formats it as a String with exactly 2 decimal places using setScale.
Show hint
price.setScale(2)
Present the Result Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A correct result that's hard to read is still a UX failure — this final lesson formats the calculator's output cleanly and assembles the complete, working class.