Float literals and their shorthand notation

25.02.2024

It annoys me when people use a shorthand notation for float literals. I see it almost every day at work, and almost every day I bite my tongue and ignore it. Let people have their preferences, I tell myself.

I am talking about writing float foo = 1.F; instead of float foo = 1.0F;. Yes it is the same, and yes it should not bother me so much, but here we are. I ask myself, what do you gain by omitting the decimal? save one keystroke? Let's try to find advantages and disadvantages of the shorthand notation.

Advantages of Shorthand notation

...by 0.00000001% every time you save one keystroke. That's it.

Disadvantages of Shorthand notation

No, seriously, it can break the visual alignment of the code.

const float foobar = 8.3F;

const float init_x = 3.5F;

const float init_y = 1.F;   // ughh...

const float init_z = 5.2F;

See how it could all have been perfectly aligned? was it worth it?


Unless your project is enforcing a given style e.g. via clang-tidy, you will be introducing inconsistent styles into your code, why? because most people don't use that shorthand notation, it is simply not the default style, sooner than later someone will push code using the normal float literal notation and the result will look ugly. 


I actually experienced this first hand. I was working in a project where some legacy libraries had to be brought up to coding guidelines, and part of it was to change all lowercase 'f' suffixes for float literals to uppercase 'F'. The junior dev did the obvious and came up with some simple regex like (\d+\.\d+)f with substitution $1F, which works pretty well to replace floating literals that dont use the shorthand notation. The inconsistent mess was only discovered some time later and swiftly corrected.


So again, what do you gain by omitting the decimal? Just don't be lazy and type the damn zero!