Redis INCRBYFLOAT Command Explained

In Redis, the INCRBYFLOAT command increments a floating point number by the specified amount. More specifically, it increments the string representing a floating point number stored at the specified key.

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

An error occurs if the key contains a value of the wrong type, or if the current key content or the specified increment are not parsable as a double precision floating point number.

Syntax

INCRBYFLOAT key increment

Where key is the key to increment, and increment is the amount to increment it by.

Example

Suppose we set a key like this:

SET balance 1.58

Result:

OK

Let’s quickly take a look at it:

GET balance

Result:

"1.58"

OK, now let’s increment it by a floating point :

INCRBYFLOAT balance 0.1

Result:

"1.68"

INCRBYFLOAT returns a bulk string reply with the new value of the key after it’s been incremented.

Negative Values

We can increment the value by a negative amount just as we can increment positive values. In other words, we can decrement the value by using a negative value.

Set a negative value:

INCRBYFLOAT balance -10.675

Result:

"-8.995"

In this case, it resulted is a negative value.

When the Key Doesn’t Exist

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

Let’s delete our balance key:

DEL balance

Result:

(integer) 1

The DEL command returns the number of keys that were deleted – in this case it’s 1.

Now let’s try to increment that (non-existent) key:

INCRBYFLOAT balance 1.12345678912345678

Result:

"1.12345678912345678"

So we can see that balance has been created again, this time with a value that’s the same that we incremented it by.

The precision of the output is fixed at 17 digits after the decimal point regardless of the actual internal precision of the computation.

When the Value is the Wrong Type

An error occurs if the key contains a value of the wrong type or contains a string that cannot be represented as a floating point number.

Let’s test this by trying to increment a value that’s not a valid float.

Set the amount:

SET balance "Ten"

Result:

OK

Let’s take a look at it:

GET balance

Result:

"Ten"

OK, now let’s try to increment it:

INCRBYFLOAT balance 1.5

Result:

(error) ERR value is not a valid float

An error occurred as expected.

Similar Commands

We can also use INCR to increment by one, and INCRBY to increment by an integer amount.

Example of INCR:

INCR balance

Example of INCRBY:

INCRBY balance 2