Samurai Jack
Samurai Jack

Reputation: 3125

Use toFixed() to remove extra digits for all elements of a matrix

I know that for an array it can be done like this:

anArray = anArray.sum.map(function(elem){
    return Number(elem.toFixed(2));
});

But how can it be done for a bi-dimensional array?

This is my approach:

aMatrix = aMatrix.reduce( function (r, a) {
    a.forEach(function (b, i, j) {
        r[i][j] = r[i][j].toFixed(2);
    });
    return r;
}, []);

I tried only to remove the extra digits first, it must be added Number() also to remove the trailing zeros.

Any ideas?

Upvotes: 0

Views: 662

Answers (3)

Elad
Elad

Reputation: 2377

The same way you loop throw the one dimensional array, you can loop throw each array inside of parent array:

var newArr = anArray.sum.map(function(elem){
    return elem.map( function( subElem ){
      return subElem.toFixed(2); 
    });
});

Or, in es6 syntax:

anArray.sum.map( sub => sub.map( subSub => subSub.toFixed(2)));

And then you don't need to return anything, just update the value inside the map function.

Upvotes: 0

Alnitak
Alnitak

Reputation: 339786

Do NOT use the results of .toFixed as actual numbers. Its sole purpose is to round numbers for presentation purposes, hence why it returns a string.

Use e.g. Math.round(n * 100.0) / 100.0 if you really must use numbers of that precision when calculating, but bear in mind that in computers' binary floating point representations of numbers it is often not possible to express those numbers exactly.

To demonstrate this, see what happens if you try to evaluate:

> (0.03).toFixed(19)
"0.0299999999999999989"

It is almost always better to use numbers without rounding them, and then only round them at display time.

If your numbers are actually representing a currency and the precise results matter (e.g. for tax calculation purposes) then you shouldn't be using floating point at all. Use integer math instead, and count in e.g. cents instead of dollars.

From the comments it appears that you actually want to display numbers with up to two decimal places, i.e. like .toFixed(2) but with trailing zeroes removed, and the manipulation of the nested 2D array is required only because you hadn't found a way to do that with an Angular directive.

To do that, IMHO it's better to remain in "string" space rather than abusing the Number constructor. You could use for example:

myvalue.toFixed(2).replace(/0+$/, '')

Upvotes: 2

Ori Drori
Ori Drori

Reputation: 191976

You can use nesting Array#map calls to get the result:

var matrix = [[1.234, 4.123123, 3.1235134512], [23.12312, 90.123123, 3.123123]];

var result = matrix.map(function(subArray){
  return subArray.map(function(elem) {
    return Number(elem.toFixed(2));
  });
});

console.log(result);

Upvotes: 0

Related Questions