ruby - Array of strings to float values can correctly sort negative numbers but same values using sprintf, kernel.format, etc. sort incorrectly -


Why can string.to_float sort a array of values ​​correctly, but those same values ​​are sorted incorrectly When '% .3f'%

I am currently working on a challenge that provides you a text file. The rows filled with numbers (example) are:

1.123 -3.010 3.999 -2.199 -1.212 2.190 4.121 0.000

My goal is to sort these numbers And print them to console them properly

Try it for the first time, divide these lines into their respective string numbers, then change them to Floating Point Value with .to_f Give, and lastly, sort them and give them one Date back to us (space delimited).

It looked something like this:

  line.chomp.split ("") .map {| e E.to_f} .sort! .join ("")   

By the time I did not realize that any number in the exact three decimal places like 68.060 has ended, then the last zero will be lost. And thus, instead of 68.060, shows as 68.060 which invalidates the solution.

I went around and found a lot of references:

  kernel.format ('% .3f', digits)   

and

  sprintf '% .3f'% num   

These were correct, they solved the problem I applied them to them like this (Tried differentiation but they used to do the same work):

  line.chomp.split ("") .map {| e sprintf '% .3f', e} .sort! .join ("")   

Then I found myself looking for another problem, though. Each row put in the console arranged the negative numbers as they were positive numbers, so instead:

-3.010 -2.199 -1.212 0.000 1.123 2.190 3.999 4.121

On the console, I was looking at:

-1.212 -2.199 -3.010 0.000 1.123 2.1 9 3.99 9 4.121

This is an I Could not find it too much It could be my fault that I do not know exactly at Google, but none of my searches was able to hit anything on the relevant. p> You are sorting the array after that you have formatted it in an array of stars, this means that your array is classifying elements, Not numerically.

You should first map your array to float values, and then sort it:

  line.chomp.split ("") .map (& amp; ;: To_f) .sort   

You can now properly format the number:

  line.chomp.split ("") .map (And: to_f) .sort.map {| e sprintf '% .3f', e}. Include ("")    

Comments

Popular posts from this blog

php - PDO bindParam() fatal error -

logging - How can I log both the Request.InputStream and Response.OutputStream traffic in my ASP.NET MVC3 Application for specific Actions? -

java - Why my included JSP file won't get processed correctly? -