how to prevent numbers from showing up in scientific notations

若如初见. 提交于 2019-11-28 12:01:47
siphr

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.


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';
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!