0

我有一个基于 istringstream 的模板函数,我发现字符串值“99999.99”四舍五入到 100000。事实上,我发现 C++ iostream 通常都在进行四舍五入。普通的 'ole 标准 C printf() 可以很好地处理这项工作。有没有办法解决这个问题。

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <unistd.h>
#include <algorithm>

using namespace std;


template <class T> bool from_string(T& t, const string& s, ios_base& (*f)(ios_base&))
{
    istringstream iss(s);
    return !(iss >> f >> t).fail();
}


class MyApp {
private :
public :
    MyApp();
    virtual ~MyApp();

    void run();

    operator bool() const { return true; }
};


MyApp::MyApp()
{
}

MyApp::~MyApp()
{
}

void MyApp::run()
{
    string elementData = "99999.99";
    double fproductUnitPrice = 0.0;
    double myval = 99999.99;
    double myval2 = 99999.95;
    float myval3 = 99999.99;

    from_string<double>(fproductUnitPrice, elementData, std::dec);
    cout <<  "fproductUnitPrice=" << fproductUnitPrice << endl;
    fproductUnitPrice -= 0.05;
    cout <<  "fproductUnitPrice=" << fproductUnitPrice << endl;
    cout <<  "myval=" << myval << endl;
    cout <<  "myval2=" << myval2 << endl;
    cout <<  "myval3=" << myval3 << endl;
    printf("myval %lf\n", myval);
    printf("myval2 %lf\n", myval2);
    printf("myval3 %lf\n", myval3);
}

int main(int argc, char* argv[])
{
    MyApp myApp;

    myApp.run();
}

编辑 - 了解使用浮点数/双精度数的要点,但没有人运行我发布的代码。printf()s 正确打印值(9999.9999 除外,它是一个浮点数)。我更多的是关于为什么 stdc 库与 C++ 的差异。

fproductUnitPrice=100000 
fproductUnitPrice=99999.9
myval=100000             
myval2=99999.9           
myval3=10000             
myval4=10000             
myval 99999.990000       
myval2 99999.950000      
myval3 10000.000000      
myval4 9999.999900       
4

0 回答 0