How can I detect if a float has a repeating decimal expansion in C#?

前端 未结 6 1933
一个人的身影
一个人的身影 2021-01-12 00:16

I simply need to know how I can detect repeating decimal expansion in floats.

Example:

0.123456789123456789

The repeating portion of the number would

6条回答
  •  时光说笑
    2021-01-12 00:23

    You can't.

    Floating-point has finite precision. Every value of type float is an integer multiple of an integer power of 2.0 (X * 2Y), where X and Y are (possibly negative) integers). Since 10 is a multiple of 2, every value of type float can be represented exactly in a finite number of decimal digits.

    For example, although you might expect 1.0f/3.0f to be represented as a repeating decimal (or binary) number, in fact float can only hold a close approximation of the mathematical value, one that isn't a repeating decimal (unless you count the repeating 0 that follows the non-zero digits). The stored value is likely to be exactly 0.3333333432674407958984375; only the first 7 or so digits after the decimal point are significant.

提交回复
热议问题