C# get digits from float variable

前端 未结 12 1657
南笙
南笙 2020-12-06 16:26

I have a float variable and would like to get only the part after the comma, so if I have 3.14. I would like to get 14 as an integer. How can I do that?

12条回答
  •  一整个雨季
    2020-12-06 17:09

    Here's the "noncheating" answer:

    double n = 3.14;
    const double precision = 0.000001;
    
    // we don't handle negative numbers very well
    if (n < 0)
        n = 0 - n;
    
    // remove the integer part of n
    n -= Math.Floor(n);
    int result = 0;
    while (n > precision)
    {
        // move 1/10th digit of n into 1's place
        n *= 10;
        // get that digit
        int digit = (int)Math.Floor(n);
        // shift result left and add digit to it
        result = result * 10 + digit;
        // remove 1's digit from n
        n -= digit;
    }
    
    // answer is in result;
    

    We use precision instead of 0 to make up for the fact that floating point numbers don't work very well with decimal numbers. You can adjust it to suit your application. This is why I think the "cheating" string way is actually better.

提交回复
热议问题