 # Ex 03 - round versus trunc

The example given for exercise 03 works as given, but if you change Zed’s height to be 78 inches, then it will compute a height of 7 feet and -6 inches. If Math.round() is changed to Math.trunc() then it computes the more traditional 6’6".

Math.floor() would also work since these should all be positive. But I think that the concept of truncation is most appropriate for this type of problem.

Ooooh, that sounds like a bug actually. Can you drop a few quick calculations in JS to show me what you found? I think floor might be better than trunc, but I could see doing both just to show it, and I may include the bug to demonstrate that problem with floats.

``````// Simple demonstration based on ex04.js
//
let height = 78;

let feet = Math.round(height / 12);
let inches = height - (feet * 12);
console.log(`With round: A height of \${height} inches is \${feet} feet \${inches} inches.`);

feet = Math.floor(height / 12);
inches = height - (feet * 12);
console.log(`With floor: A height of \${height} inches is \${feet} feet \${inches} inches.`);

feet = Math.trunc(height / 12);
inches = height - (feet * 12);
console.log(`With trunc: A height of \${height} inches is \${feet} feet \${inches} inches.`);

// Try with negative numbers too

height = -78;

feet = Math.round(height / 12);
inches = height - (feet * 12);
console.log(`With round: A height of \${height} inches is \${feet} feet \${inches} inches.`);

feet = Math.floor(height / 12);
inches = height - (feet * 12);
console.log(`With floor: A height of \${height} inches is \${feet} feet \${inches} inches.`);

feet = Math.trunc(height / 12);
inches = height - (feet * 12);
console.log(`With trunc: A height of \${height} inches is \${feet} feet \${inches} inches.`);
``````

When run this displays:

``````With round: A height of 78 inches is 7 feet -6 inches.
With floor: A height of 78 inches is 6 feet 6 inches.
With trunc: A height of 78 inches is 6 feet 6 inches.
With round: A height of -78 inches is -6 feet -6 inches.
With floor: A height of -78 inches is -7 feet 6 inches.
With trunc: A height of -78 inches is -6 feet -6 inches.
``````

Math.trunc looks like the easiest way to demonstrate how break a number into whole and fractional units.

A free service run by Zed A. Shaw for learncodethehardway.org.