Convert strings from number to string in awk

I have a command awkthat also gives the specified result.

echo '1600000.00000000' '1600000.0000' | awk '{ print ($1 != $2) ? "true" : "false" }'

Result: - false

According to the numerical value, the result specified by the command is correct. But I want the team to consider both inputs ( '1600000.00000000' '1600000.0000') as stringand give the result as true. Because if you consider both inputs as string, then they are not equal, the difference is accuracy.

+4
source share
2 answers

From the GNU Awk User Guide, to make a number convert to a string, combine that number with an empty string ""

$ echo '1600000.00000000' '1600000.0000' |
  awk '{ print ($1"" != $2"") ? "true" : "false" }'
+5
source

You can also use sprintf:

echo '1600000.00000000' '1600000.0000' |\
awk '{ print(sprintf("%f",$1) == sprintf("%f",$2)) ? "true": "false"}'
true
0
source

Source: https://habr.com/ru/post/1687996/


All Articles