-2

This is my code:

float = 10.23444566
awk {printf("%.0f\n", $float)}

I am getting the answer as 0.

I just want to get the value 10 out of it.

i am using awk command .

Aakash k.u.
  • 65
  • 1
  • 8
  • [How to convert floating point number to integer?](https://unix.stackexchange.com/q/89712/56041), [Convert floating point variable to integer?](https://stackoverflow.com/q/1362298/608639), [Convert floating point numbers to integer without rounding in bash](https://stackoverflow.com/q/28437129/608639), etc. – jww Mar 09 '18 at 03:32
  • Possible duplicate of [Convert floating point variable to integer?](https://stackoverflow.com/questions/1362298/convert-floating-point-variable-to-integer) – koosa Mar 09 '18 at 05:21

3 Answers3

1

Try this.

float=10.23444566;
printf "%.0f" $float;

In shell scripting, the syntax you used for printf command is wrong. You cannot call it like a c function.

See man pages for details.

man printf

 

EDIT

If you want to use the awk command, you need to pipe the float value to the command. See the code below.

float=10.23444566;
echo $float | awk  '{printf "%.0f\n", $1}';
Vivek
  • 2,665
  • 1
  • 18
  • 20
1

I believe this is the answer the OP is looking for:

> float=10.23444556; echo $float | awk '{ printf "%d\n",$1 }'
10 
>

This is similar:

> float=10.2344456; awk -v x="${float}" 'BEGIN{ printf "%d\n", x }'
10
>
hdahle
  • 51
  • 5
  • This should be the correct answer. Note that if the floating point is > 0.5, the `awk '{printf "%.0f\n", $1}'` command will do a ROUND up and will NOT return the integer part, but the rounded number; up or down. – peixe Feb 16 '21 at 14:16
0

Well, the (Posix-)Shell does not have floating points, and when we talk about floats, it makes sense to talk about mantissa and exponent, and it is unclear what you mean by "integer" part.

Also, your statement to assign to the variable float is syntactically wrong, so you would get already an error message at this point.

If you have a string, which might not look like a float, but at least like a fractional number (as it is in your example), and you want to extract the part to the left of the fractional point, this goes like this:

float=10.45671
int_part=${float%.*}

You need to think about the cases, where you have a negative number, or when you really have something which looks like a general float, i.e. 12.157E+03.

user1934428
  • 19,864
  • 7
  • 42
  • 87