Is there a way to return the amount of decimal places a float currently has?
For example:
getPrecision(42.123f); // returns 3
getPrecision(42.123456f); // returns 6
getPrecision(42.01f); // returns 2
getPrecision(42.0f); // returns 0
Is there a way to return the amount of decimal places a float currently has?
For example:
getPrecision(42.123f); // returns 3
getPrecision(42.123456f); // returns 6
getPrecision(42.01f); // returns 2
getPrecision(42.0f); // returns 0
Is there a way to return the amount of decimal places a float currently has?
getPrecision(42.123f); // returns 3
Your understanding of "the amount of decimal places a float currently has" is flawed. Floating point representations have finite precision and cannot represent all rational numbers. Most commonly, they are represented in a binary format and many decimal base numbers that appear simple to you are not representable.
Assuming the most common IEEE-754 binary 32 bit representation, 42.123 is not a representable number. When you write 42.123f, the compiler will use the closest representable number instead. In this case, that happens to be 42.1230010986328125 which is very close to 42.123 but isn't quite exact. You may notice that the number that you get does not have "3 decimal places". There is no way to write such function getPrecision
that would output 3 for 42.123f, and the accurate result for all other potential values unless the floating point representation can precisely represent all of those values.
If getting the output 16 that matches the actually represented value is what you're looking for, then the answer is: Yes, such function could be written, but how would it be useful?
A representation where counting decimal places makes sense is text. You can count the number of charecters between '.'
and 'f'
given the string "42.123f"
.
No, because that is often meaningless.
You see, floating-point numbers use base-2 fractions, not base-10. For example, the base-2 fraction 0.01 is 1/4, i.e. one-quarter of a unit.
There are base-10 values which are simply not representible by a (finite-sized) floating-point number - even with few base-10 digits. Take 0.2
, or 1/5; what is its base-2 fractional representation? It's infinitely long. Just like 1/7 has an infinitely-long base-10 representation. Thus, the floating-point value you'll get when you write 0.2f
has a value that's not equal to 0.2; and whatever "decimal places" value you obtain from it will not really regard 0.2.