I have a string
let input = "1.0 2.5 3.0 4.5 5.0 -5.5 4.5 3.0 -2.0 -1.0 1.0 2.0 5.0";
In order to get a number array, I tried to do the following:
let output= input.split(" ").map(Number);
So now i got a number array. However, using the following code, I failed to format all numbers with one decimal place:
for (i = 0; i < output.length; i++) {
output[i].toFixed(1);
}
let input = "1.0 2.5 3.0 4.5 5.0 -5.5 4.5 3.0 -2.0 -1.0 1.0 2.0 5.0";
let output = input.split(" ").map(Number);
console.log(output); //got a number array
for (i = 0; i < output.length; i++) {
output[i].toFixed(2);
}
console.log(output); //try to get all numbers with one decimal place,but failed
Can anyone know how to make this? Thanks in advance.
You need an assignment or map the new values.
let input = "1.0 2.5 3.0 4.5 5.0 -5.5 4.5 3.0 -2.0 -1.0 1.0 2.0 5.0";
let output= input.split(" ").map(Number).map(v => v.toFixed(1));
console.log(output);
As mentioned in comments by Terry, you could combine the last both mappings into one.
let input = "1.0 2.5 3.0 4.5 5.0 -5.5 4.5 3.0 -2.0 -1.0 1.0 2.0 5.0";
let output= input.split(" ").map(v => Number(v).toFixed(1));
console.log(output);