C/C++ counting the number of decimals?

后端 未结 13 1986
北荒
北荒 2020-12-06 16:04

Lets say that input from the user is a decimal number, ex. 5.2155 (having 4 decimal digits). It can be stored freely (int,double) etc.

Is there any

13条回答
  •  时光说笑
    2020-12-06 16:35

    This is a robust C++ 11 implementation suitable for float and double types:

    #include 
    #include 
    #include 
    
    template 
    std::enable_if_t<(std::is_floating_point::value), std::size_t>
    decimal_places(T v)
    {
        std::size_t count = 0;
    
        v = std::abs(v);
    
        auto c = v - std::floor(v);
    
        T factor = 10;
    
        while (c > 0 && count < std::numeric_limits::max_digits10)
        {
            c = v * factor;
    
            c = c - std::floor(c);
    
            factor *= 10;
    
            count++;
        }
    
        return count;
    }
    

    It throws the value away each iteration and instead keeps track of a power of 10 multiplier to avoid rounding issues building up.

提交回复
热议问题