-5
int main()
{
    double number = 4, intPart, fractPart;
    fractPart = modf(number, &intPart);
    string stringIntPart = to_string(intPart);
    
    cout << fractPart << endl << intPart << endl << stringIntPart;

    return 0;
}

As an output I have: 0 (fractPart) 4 (intPart) 4.000000 (stringIntPart) So why do I have these zeroes at stringIntPart and how to get rid of it? Thank you

cryon234
  • 13
  • 3
  • As if you had done `std::sprintf(buf, "%f", value)`. – Eljay Oct 26 '22 at 20:14
  • 5
    Well, you declared `intPart` as a `double`, so its string representation contains digits after the decimal point, like for any floating-point number – ForceBru Oct 26 '22 at 20:14
  • 1
    Your variables are of type `double`, which is a floating point type, and `modf()` works with floating point values. String representation of floating point values is formatted - by default - to include decimal point and trailing digits. Hence "those zeros".\ – Peter Oct 26 '22 at 20:25
  • This doesn't address the question, but you don't need the extra stuff that `std::endl` does; `'\n'` ends a line. – Pete Becker Oct 26 '22 at 21:27

1 Answers1

3

intPart is still a double, and gets formatted for text output with the default rules for doubles (just because it's logically an integer value doesn't mean C++ is willing to spend the effort to do runtime checks to tweak precision dynamically; that's your responsibility if you choose to take it on).

To fix, you can either cast it to an integer type (risks losing data if the integer component is larger than 64 bits), or you can use iomanip manipulators to change the formatting rules for floating point values so they omit the data after the decimal point that you know will not exist, e.g. with:

cout << fractPart << endl << std::fixed << std::setprecision(0) << intPart << endl << stringIntPart;

(I left the std:: prefixes in there on the added stuff, because using namespace std; is a bad idea, and I prefer being explicit)

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271