Search code examples
javascriptformattingtostringnumber-formatting

converting array to string in javascript while controlling precision of floats


I have a javascript array-of-number-triples, of the form

[[123.55555,4.44444444,0.123455666],[12344.44444,7.77777777,8.8888101010],...,[1.000102340240,123.02020400,1.121212121212]]

This converts nicely to a string with the 'toString()' method. (Edit: Actually, the two-dimensional nature of the array is lost by 'toString()', but it doesn't bother me because each line has 3 numbers, so that structure is still implicit in the string.)

However, what if I want to truncate/round (I don't really care which) the numbers at 2 or 3 decimal places? It seems like 'toFixed()' doesn't work for arrays...

Nb: I'm aware that I could loop through the array and truncate each number manually and piece together the resulting strings, but I'm hoping there's a more elegant way...


Solution

  • As commented; you can use map:

    console.log(
      [[123.55555,4.44444444,0.123455666],[12344.44444,7.77777777,8.8888101010],[1.000102340240,123.02020400,1.121212121212]]
      .map(numbers=>numbers.map(number=>number.toFixed(3)))
      .toString()
    )