问题
Is there any efficient way (without converting the float into a string) to obtain the number of digits a floating-point number consists of (independent of its length and precision) ?
On that way I can implement a fairly good, portable, problematic-less function for comparison/conditioning by multiplying the float by the number of the digits it consists of.
回答1:
Q: Is there any efficient way to obtain the number of digits a floating-point number?
A: I doubt it.
Every finite FP number is exact, but maybe not the exact value one thinks.
Due to typical binary64 implementation of a double
,double x = 0.53
, x
value: .5300000000000000266453525910037569701671600341796875
, 52 digits.double x = 0.1
, x
value:.1000000000000000055511151231257827021181583404541015625
55 digits.
The next closest double
to mathematical 0.1
is .09999999999999999167332731531132594682276248931884765625
with 56 digits.
DBL_MAX
: in decimal, typically about 300 digits 17976931348623158...
ending with 6728515625.
.
DBL_MIN
: typically 0.000000(~300 zeros) 22250738585072014... (maybe about 700 more digits)
.
Comparison of FP numbers need not determine the number of digitis in its decimal representation. To compare FP numbers, use the usual relationship operators >, >=, ==
, etc.
Theses values are illustrative. YMMV.
来源:https://stackoverflow.com/questions/31690417/count-the-number-of-digits-of-a-floating-point-number