round() for float in C++

后端 未结 22 1644
时光取名叫无心
时光取名叫无心 2020-11-22 03:01

I need a simple floating point rounding function, thus:

double round(double);

round(0.1) = 0
round(-0.1) = 0
round(-0.9) = -1

I can find

22条回答
  •  一整个雨季
    2020-11-22 03:23

    // Convert the float to a string
    // We might use stringstream, but it looks like it truncates the float to only
    //5 decimal points (maybe that's what you want anyway =P)
    
    float MyFloat = 5.11133333311111333;
    float NewConvertedFloat = 0.0;
    string FirstString = " ";
    string SecondString = " ";
    stringstream ss (stringstream::in | stringstream::out);
    ss << MyFloat;
    FirstString = ss.str();
    
    // Take out how ever many decimal places you want
    // (this is a string it includes the point)
    SecondString = FirstString.substr(0,5);
    //whatever precision decimal place you want
    
    // Convert it back to a float
    stringstream(SecondString) >> NewConvertedFloat;
    cout << NewConvertedFloat;
    system("pause");
    

    It might be an inefficient dirty way of conversion but heck, it works lol. And it's good, because it applies to the actual float. Not just affecting the output visually.

提交回复
热议问题