Cross platform/compiler consistent sprintf of floating point numbers

Spread the love

Question Description

We have a game that needs to be deterministic as it is part of its multiplayer model. We also use Lua, which uses the sprintf internally (the format is %.14g).

The problem arises when it prints number like 0.00001. In some cases it prints 1e-05 and in some other cases, it prints 1e-005 (extra zero).

For example when compiled with Visual studio 2015 it prints 1e-005, and with Visual studio 2013 it prints 1e-05. I tried different locale settings, but it doesn’t seem to have any effect.

The question is: What is the best solution to achieve deterministic results?
I don’t really care if the scientific notation is standardized, or eliminated.

Solutions I thought about:

  • When I use the %f notation, it doesn’t ignore the insignificant zeroes, so having %.14f would result into impractically long numbers.
  • Using custom sprintf method (copy pasted from some of the standard libraries)
  • Using some special format I didn’t thought about (I use only this as reference:

Practice As Follows

A year later, this is how we solved it.

We downloaded custom print implementation (trio) and forced usage of this implementation instead of the system one in the lua (and our sources).

We also had to change

long double trio_long_double_t;


double trio_long_double_t;

in the triodef.h to ensure the Visual studio and linux/mac gives the same results.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.