 # Truncation of floats in server.log()?

#1

I know that floating point isn’t exact. If you didn’t know that, you need to read http://floating-point-gui.de/

I’m trying an example from https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/

``````local f = 0.1;
local sum = 0.0;

for (local i = 0; i < 10; ++i) {
sum += f;
}
server.log("sum = " + sum + "\n");
local product = f * 10.0;
server.log("product = " + product + "\n");

if (sum == product) {
server.log("Equal\n");
}
else {
server.log("Not equal\n");
}
``````

And it’s logging the following:

``````2017-08-15 13:54:05 +01:00	[Agent]	sum = 1
2017-08-15 13:54:05 +01:00	[Agent]	product = 1
2017-08-15 13:54:05 +01:00	[Agent]	Not equal
``````

I don’t have a problem with the “Not equal”. My question is this:

What are the semantics for printing floating point numbers with server.log()?

It displays both floating point numbers as `1`. If I try similar squirrel code locally (with `print` instead of `server.log`), and I throw an exception, I get:

``````LOCALS
[product] 1
[sum] 1.0000001192093
[f] 0.10000000149012
``````

So I know that the precision’s in there. Where did it go?

#2

When a float is coerced to a string (e.g. as operand to “+” when the other operand is a string, or as lone parameter to string functions such as server.log), then the implicit “printf-style” format used is “%f”, which as in C has a precision of 6. Any float that’s equal to 1.00000 to 6 significant figures, coerces to the string “1”. If you want to use the full power of printf (e.g. to add extra precision), you can take control of the conversion by using format(), rather than relying on coercion.

Note that on the device, floats are IEEE754 single precision, so may have fewer significant digits than you hope.

Peter