how to prevent numbers from showing up in scientific notations

前端 未结 3 637
囚心锁ツ
囚心锁ツ 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: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( static_cast(value*1000) ) / 1000
    // case techk::PROC_DOUBLE:
    static_cast( static_cast(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.


提交回复
热议问题