4

I'm trying to sum floats which use the comma as separator, and gawk does integer calculations. Here's the script:

BEGIN {
  FS=";"
  OFS=";"
  CONVFMT = "%2.2f"
}
{ 
  print $1
  print $2
  print $1+$2 
}

I'm using this data file:

4,3;5,7

and calling the script like this:

LC_ALL=fr_BE gawk -f test.awk < t.txt

I get this output:

4,3
5,7
9

I have the fr_BE locale set up, but the result is still incorrect. How can I fix this?

2 Answers 2

7

The answer is to use the --use-lc-numeric gawk option.

--use-lc-numeric

This forces gawk to use the locale's decimal point character when parsing input data. Although the POSIX standard requires this behavior, and gawk does so when --posix is in effect, the default is to follow traditional behavior and use a period as the decimal point, even in locales where the period is not the decimal point character. This option overrides the default behavior, without the full draconian strictness of the --posix option.

Example

Say we have this data file:

$ cat t.txt 
4,3;5,7
4,9;5,7

To ease in seeing the output, I changed this line in test.awk:

print "Total: "$1+$2 

Now when you run it using the above mentioned switch:

$ LC_ALL=fr_BE gawk --use-lc-numeric -f test.awk < t.txt
4,3
5,7
Total: 10
4,9
5,7
Total: 10,60

References

5
  • I think this solution will not work. gawk can not convert string 4,3 to float number. Commented Mar 23, 2014 at 13:06
  • @Gnouc do you think or know it? I tried it with gawk 3 an 4 and it seems to work.. Commented Mar 23, 2014 at 16:34
  • I try with gawk 3.1.8, Ubuntu 12.04 and it does not work. Commented Mar 23, 2014 at 16:40
  • It does work with gawk 4.0.1, Ubuntu 14.04. Commented Jan 11, 2016 at 21:07
  • Might not work with LC_ALL=fr_BE, though. Try LC_ALL=fr_BE.UTF-8. Commented Mar 13, 2016 at 16:56
1

I think the problem is gawk can not convert string 4,3 to a float number. You can fix it by replace , with .. For @glenn jackman input:

BEGIN {
  FS=";"
  OFS=";"
  CONVFMT = "%2.2f"
}
{
  gsub(",",".",$0)
  print $1
  print $2
  print $1+$2
}

$ LC_ALL=fr_BE gawk -f test.awk < file
4.3
5.7
10
4.9
5.7
10.6

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.