Search code examples
sortingawkfloating-pointlocale

Negative floating point numbers are not sorted correctly using awk or sort


For some reason, comparisons of negative floating point numbers with awk and sort seem to be broken on my machine. It seems that -0.1 < -0.2.

When I try to sort

0.2
-0.1
-0.2
0.1
0

using sort -n test.dat, I get

-0.1
-0.2
0
0.1
0.2

instead of

-0.2
-0.1
0
0.1
0.2

What is wrong with me?


Solution

  • Answer: You are French!

    In french, the decimal point is a comma (,) and not a dot (.). You need to either replace the dots with commas or change your locale.

    Try LC_NUMERIC=us_EN.UTF-8 sort -n test.dat and you should get the expected result.

    For your information, LC_NUMERIC is an environment variable that contains the locale to use for formatting non-monetary numbers.