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

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

    Personally I would convert it to a String, snag the substring of everything after the period, then convert to the data type you need it in. For example (It's been years since I wrote any C# so forgive any syntax problems):

    float checkNumber = 8.1234567;
    String number = new String( checkNumber ); // If memory serves, this is completely valid
    int position = number.indexOf( "." ); // This could be number.search("."), I don't recall the exact method name off the top of my head
    if( position >= 0 ){ // Assuming search or index of gives a 0 based index and returns -1 if the substring is not found
        number = number.substring( position ); // Assuming this is the correct method name to retrieve a substring.
        int decimal = new Int( number ); // Again, if memory serves this is completely valid
    }
    

提交回复
热议问题