3

I have a variable as a string:

var="50.335"

I try to convert it to int like this:

var=$(printf "%.0f\n" "$((var))")

and echo it out:echo $var But I get this error:

syntax error: invalid arithmetic operator (error token is ".335")

I need it to be an integer to be able to perform different operations with it. How can I convert it?

1 Answer 1

6

You are doing printf "%.0f" "$(( 50.335 ))" and $(( )) just accepts integers.

Just say:

$ var="50.335"
$ printf "%.0f\n" "$var"
50

From man bash:

Arithmetic Expansion

Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is:

$((expression))

The expression is treated as if it were within double quotes, but a double quote inside the parentheses is not treated specially. All tokens in the expression undergo parameter and variable expansion, command substitution, and quote removal. The result is treated as the arithmetic expression to be evaluated. Arithmetic expansions may be nested.

The evaluation is performed according to the rules listed below under ARITHMETIC EVALUATION. If expression is invalid, bash prints a message indicating failure and no substitution occurs.

And then:

ARITHMETIC EVALUATION

The shell allows arithmetic expressions to be evaluated, under certain circumstances (...). Evaluation is done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged as an error.


Note you can also use Shell parameter expansion to remove everything from the dot .:

$ var="50.335"
$ echo ${var%\.*}
50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .