Fixed Decimal Places With Last Digit Rounding Down

As a programmer or designer, sometimes you need to set a fixed number of decimal places on dynamically generated numbers.

Take the example of dividing a page element into six equal columns and let’s round the column width as a precentage to four decimal places. Pretty easy – the width of each column is 100 / 6 = 16.6667%. You can then assign the width to each of the columns with the CSS declaration of ‘width : 16.6667%;’

Houston, we have a problem.

According to my trusty Casio fx-82, 16.6667 x 6 = 100.0002. This will result in a broken layout as the total width of all the columns is greater than 100%.

You could fix this with overflow-x : hidden;, but this is a hack and may have other repercussions, and in my view it’s usually better to attack the cause of the problem, not try and hide the symptom.

Here’s a simple way to fix the problem – always round down the final digit instead of allowing it to round up like in the case of this example. In this example, 6 x 16.6666% = 99.9996% which will appear as 100% for all intents and purposes and will not break your layout.

The following javascript snippet shows an easy way to do this (using four decimal places):

var percentage_array = [];
var num = 6;
for (i = 1; i <= num; i++){
  percentage_array.push((Math.floor(100/num * i * 10000)/10000).toFixed(4)); // truncates to 4 decimal places with the last place always rounded down instead of possibly up
}
// do useful stuff with your 16.6666 values...

Leave a Reply

Your email address will not be published. Required fields are marked *