Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I get every one decimal place number in a string input

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading