how to prevent numbers from showing up in scientific notations

前端 未结 3 626
囚心锁ツ
囚心锁ツ 2020-12-11 02:23

We have a StreamBuffer class in which we haven\'t implemented std::fixed operations and I am trying to prevent number showing up in scientific nota

相关标签:
3条回答
  • 2020-12-11 02:46

    Just use snprintf:

    #include <cstdio>
    #include <limits>
    #include <iostream>
    
    int main() {
        double value = 0.1234567890123456789;
        const int Precision = std::numeric_limits<double>::digits10;
        const std::size_t StringBufferSize = Precision + 3; // sign, dot and terminating zero.
        char str[StringBufferSize];
        std::snprintf(str, StringBufferSize - 1, "%.*f", Precision, value);
        str[StringBufferSize - 1] = 0;
        // buf << "{\"double\":" << str << "}";
        std::cout << str << '\n';
    }
    
    0 讨论(0)
  • 2020-12-11 02:57

    StreamBuffer class must inherit from std::ios_base (or some of it's derivatives such as std::ostream) for your expected behaviour. std::fixed can only work with derivative implementations of what is available as part of the STL.

    Additionally, if you have access to an std::ios_base, you can also play around with std::ios_base::precision.

    If you are stuck in a situation where you cannot update the class then the most commonly used and traditional way is by way of scaling floats. In the interest of reducing duplication please have a look at the already answered question here. For example, for a 3rd degree of precision, I'd replace all 'value' instances with:

    // case teck::PROC_FLOAT:
    static_cast<float>( static_cast<int>(value*1000) ) / 1000
    // case techk::PROC_DOUBLE:
    static_cast<double>( static_cast<long long>(value*1000) ) / 1000
    

    Having better understood the questioner's requirements. I have realised that the above would not work with exponents. In order to get around this I propose doing the following:

    case teck::PROC_FLOAT:
            std::stringstream ss;
    
            ss << std::fixed << value;
            buf << "{\"float\":" << ss.str() << "}";
            break;
    

    This, however, will most certainly allocate more memory.


    0 讨论(0)
  • 2020-12-11 03:01

    It looks to me like maybe you should try CppFormat. There are some examples of how to use it for formatting here.

    0 讨论(0)
提交回复
热议问题