Question: how do you display a decimal numbers to a specified number of decimal places without rounding?

See after running the calculations what I get back is something like this

X: -2.9513513513513514 km

Y: -4.173513513513513 km

Z: -16.323243243243244 km

Obviously this is not desirable so I’d like to truncate these numbers to 2 decimal places so instead of the output above I get

X: -2.95 km

Y: -4.17 km

Z: -16.32 km

The problem that I’m running into is that I can’t find a way to truncate decimal numbers to a specified number of decimal places without rounding.

.trunc(); doesn’t work as it doesn’t provide a optional parameter to specify at what point you want to start dropping digits, it just drops all digits after the decimal point obviously this is only useful when the number is small enough that I’m displaying in meters instead of kilometres as I don’t need the numbers after the decimal point in that case.

.toFixed(2) doesn’t work either as that rounds meaning the displayed coordinates are wrong

.toPrecision(3) doesn’t work either for the same reason it appears to round thus resulting in incorrect coordinates being displayed

for example

X: -2.747027027027027 km displays as X: -2.75 km

When it should display as X: -2.74 km

I’m aware of the fact that due to the way computers work not all fractional numbers can be accurately represented and this is a problem in all languages not just JavaScript thus I’d like to avoid the whole issue by simply not rounding at all but it seems that what should be a stupidly easy task is actually devilishly tricky, and unfortunately a lot of what I have found online while looking for a solution to this is unnecessarily complicated and I don’t understand it.

in any event here is what I have so far

Code: Select all

```
var x_coordinate = icons[target]['x'] / 222 / 1000;
var y_coordinate = icons[target]['y'] / 222 / 1000;
var z_coordinate = icons[target]['z'] / 222 / 1000;
if(x_coordinate > 0 && x_coordinate < 1 || x_coordinate < 0 && x_coordinate > -1 || x_coordinate == 0)
{
var x_coordinate = x_coordinate * 1000;
table.rows[0].cells[2].innerHTML = Math.trunc(x_coordinate) + " m";
}
else
{
table.rows[0].cells[2].innerHTML = x_coordinate + " km";
}
if(y_coordinate > 0 && y_coordinate < 1 || y_coordinate < 0 && y_coordinate > -1 || y_coordinate == 0)
{
var y_coordinate = y_coordinate * 1000;
table.rows[1].cells[2].innerHTML = Math.trunc(y_coordinate) + " m";
}
else
{
table.rows[1].cells[2].innerHTML = y_coordinate + " km";
}
if(z_coordinate > 0 && z_coordinate < 1 || z_coordinate < 0 && z_coordinate > -1 || z_coordinate == 0)
{
var z_coordinate = z_coordinate * 1000;
table.rows[2].cells[2].innerHTML = Math.trunc(z_coordinate) + " m";
}
else
{
table.rows[2].cells[2].innerHTML = z_coordinate + " km";
}
```