How to Increment a Floating Point Number in Redis

The INCR command is commonly used in Redis to increment a value by one. And the INCRBY command can be used to increment a valued by a specified integer. But neither of those commands let us work with floating point numbers.

If we want to use floating point numbers, we can use the INCRBYFLOAT command.

Example

Suppose we have the following key called duration:

GET duration

Result:

"10.25000000000000067"

That value is a floating point number.

We can use the INCRBYFLOAT command to increment that value by another floating point number:

INCRBYFLOAT duration 1.10000000000000001

Result:

"11.35000000000000068"

We can also increment the floating point number by an integer if we require:

INCRBYFLOAT duration 1

Result:

"12.35000000000000068"

And we can increment an integer by a floating point number. Let’s get the initial value from another key:

GET age

Result:

"10"

Now increment that integer by a floating point number:

INCRBYFLOAT age 1.25

Result:

"11.25"

When the Key Doesn’t Exist

If the key doesn’t exist, INCRBYFLOAT creates it with a value of zero, then increments it by the specified amount:

INCRBYFLOAT distance 32.5678

Result:

"32.5678"