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

前端 未结 6 1966
一个人的身影
一个人的身影 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:38

    You can isolate the fractional (post-period) part of the number like this:

    value - Math.Floor(value)
    

    If you do this with the double value "1.25", you'll end up with the value "0.25". Thus, you'll have isolated the part "to the right of the period". Of course, you'll have it as a double between 0 and 1, and not an integer as your question seems to require.

    Your question states that you need to "detect periods in floats". If all you need is to determine if a fractional part exists, the following code will approximately work:

    value != Math.Floor(value)
    

提交回复
热议问题