Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux sort doesn't work with negative float numbers

How to sort this kind of input?

0.00159265291648695254
-0.00318530179313823899
0
0.00999983333416666468
0.00362937767285478371
0.00477794259012844049
-0.00637057126765263261
0.00681464007477014026
-0.00840724736714870645
-0.00522201549675090458

Either sort -n data and sort -g data procudes this:

0
0.00159265291648695254
-0.00318530179313823899
0.00362937767285478371
0.00477794259012844049
-0.00522201549675090458
-0.00637057126765263261
0.00681464007477014026
-0.00840724736714870645
0.00999983333416666468

On the other hand -1.whatever would be in front of the zero. I need the sort to notice the minus signs. Thank you.

like image 442
tsusanka Avatar asked Apr 05 '12 15:04

tsusanka


3 Answers

I have the same issues. For numbers between 1.0 and -1.0. sort -n (or -g) does not solve it. I finally multiplied everything with a large number, sorted it, and divided it again. Nevertheless, I cannot understand why there would be such an error in linux

like image 174
Martijn Avatar answered Oct 05 '22 22:10

Martijn


All those troubles did my local settings. My ubuntu is in Czech:

$ echo $LANG
cs_CZ.UTF-8

In this local setting it's not a decimal point, rather a decimal comma that seperates integer from the rest (as we were thought in math classes, in our language we really do write comma instead of a point).

Therefore:

echo '0,03 >> 0,4 >
> -0,3 >
> 0' | sort -n
> 0
> -0,3 >
> 0,4 >
0,03 >

If you are writing a bash script, set the sorting routine to use the "normal" settings.

export LC_ALL=C
like image 28
tsusanka Avatar answered Oct 06 '22 00:10

tsusanka


The problem may be in your sort command. If I run the same my result is as expected:

$ echo '0.00159265291648695254
> -0.00318530179313823899
> 0
> 0.00999983333416666468
> 0.00362937767285478371
> 0.00477794259012844049
> -0.00637057126765263261
> 0.00681464007477014026
> -0.00840724736714870645
> -0.00522201549675090458' | sort -n
-0.00840724736714870645
-0.00637057126765263261
-0.00522201549675090458
-0.00318530179313823899
0
0.00159265291648695254
0.00362937767285478371
0.00477794259012844049
0.00681464007477014026
0.00999983333416666468

You shoud use GNU sort if not using it

sort (GNU coreutils) 5.93
Copyright (C) 2005 Free Software Foundation, Inc.
This is free software.  You may redistribute copies of it under the terms of
the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.
There is NO WARRANTY, to the extent permitted by law.

Written by Mike Haertel and Paul Eggert.
like image 22
Diego Torres Milano Avatar answered Oct 06 '22 00:10

Diego Torres Milano