Rounding for Display With toFixed()

The batch planner now reads tonight’s order as a number. What’s left is the four output lines, the part the head roaster looks at. In Python, most of them use an f-string spec such as {green_kg:.1f}, which rounds the value for display without touching the value itself.

JavaScript’s template literals have no format specs, so every :.1f and :.2f needs a new home. In this lesson, you’ll give it one with .toFixed() and learn why its result belongs on the output line.

Turn a Format Spec Into .toFixed()

The Python script, batch_plan.py, prints the weight of the green beans to one decimal place. Here’s that line with the settings it needs, leaving percentage formatting for the next lesson:

Language: Python
order_kg = 37.5
WEIGHT_LOSS = 0.15

green_kg = order_kg / (1 - WEIGHT_LOSS)
print(f"Green beans: {green_kg:.1f} kg")

In JavaScript, every number has a .toFixed() method that takes the number of decimal places, so {green_kg:.1f} becomes greenKg.toFixed(1) inside a ${} placeholder in the template literal. This port also asks typeof what comes back:

Language: JavaScript
const orderKg = 37.5;
const WEIGHT_LOSS = 0.15;

const greenKg = orderKg / (1 - WEIGHT_LOSS);

console.log(`Green beans: ${greenKg.toFixed(1)} kg`);
console.log(typeof greenKg.toFixed(1), typeof greenKg);

The first line matches Python’s, and the second holds the key fact of this lesson:

Language: Program Output
Green beans: 44.1 kg
string number

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.