Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String conversion from numeric to string in awk

Tags:

bash

unix

awk

I have below awk command which give mentioned result as well.

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

Result is : - false

As per numeric value the result given by the command is correct. But I want command must consider both input('1600000.00000000' '1600000.0000') as string and give the result as true. Because If you consider both input as string then they are not equal difference is there in precision.

like image 455
Amol Murkute Avatar asked Oct 23 '17 09:10

Amol Murkute


People also ask

What is the use of awk command?

The awk command is a Linux tool and programming language that allows users to process and manipulate data and produce formatted reports. The tool supports various operations for advanced text processing and facilitates expressing complex data selections.

How do I find the length of a string in awk?

awk length(string) Function: The length() function calculates the length of a string. Explanation: Length of the string also includes spaces. 3. awk substr(s, p, n) Function: The length() function is used to extract substring function from a string.


2 Answers

From the GNU Awk user's guide, to force a number to be converted to a string, concatenate that number with the empty string ""

$ echo '1600000.00000000' '1600000.0000' |
  awk '{ print ($1"" != $2"") ? "true" : "false" }'
like image 164
etopylight Avatar answered Oct 02 '22 05:10

etopylight


You can also use sprintf:

echo '1600000.00000000' '1600000.0000' |\
awk '{ print(sprintf("%f",$1) == sprintf("%f",$2)) ? "true": "false"}'
true
like image 36
Tiago Lopo Avatar answered Oct 02 '22 06:10

Tiago Lopo