C++ Integer division vs floating point division, was: Can't convert double to string


I am using DEV C++ ver 5.11. I wrote the following to convert double numbers to strings (I took the code from here: https://stackoverflow.com/questions/19690630/converting-double-to-string ). For some reason, the decimal part is truncated. Anybody can help me with this?

string numtostr(double x) {
ostringstream x_convert;
x_convert << x;
return x_convert.str();

I think I will try to call the Amibroker function numtostr() from inside the plugin. I already spent 3 hours on searching the C++ manuals.

situation 1: numtostr(2.345) works fine.

situation 2: numtostr(19/17) returns integer 1. Maybe some kind of implicit casting.

I don't need to search it further. I can work with situation 1.

If you're still interested, you could try this:

numtostr(19.0 / 17.0)

Integer division yields an integer result. Floating point division yields a floating point result. When a literal number has a decimal point, it is a floating point number, not an integer.

1 Like

Obviously. I was sure it was the other way around, probably from other languages I have used. Thank you.

For the record, here is the cpp version that uses the Amibroker numtostr function:

string ABnumtostr(float x) {

    AmiVar args[ 4 ];

    args[ 0 ].type = VAR_FLOAT;
    args[ 0 ].val = x;

    args[ 1 ].type = VAR_FLOAT;
    args[ 1 ].val = 1.5;

    args[ 2 ].type = VAR_FLOAT;
    args[ 2 ].val = true;

    args[ 3 ].type = VAR_FLOAT;
    args[ 3 ].val = false;

    AmiVar result = gSite.CallFunction("NumToStr", 4, args );

    return result.string;

Only in C/C++ / (division) has different semantics depending on type of arguments.

In AFL if you use / you are ALWAYS getting fraction.

That is why I write: do NOT write DLLs. There are differences between C/C++ and AFL that makes it 20x more likely for newbie to shoot him/herself in the foot when writing in C/C++.

Also don't use C++ streams. They are slow and bulky. If you want to convert double to string there are much faster ways, as for example C function:

double x = 123.1231;
char buffer[ 16 ];
sprintf( buffer, "%g", x );

sprintf() is faster and much more usable (with its many formatting options) than streams.

Although not a newbie, I never became good at C++ and it is already taking me 20x-50x to make the same code in C++ than in AFL. And it is a nightmare to debug them. I just select to make some plugins when it is purely loops (no array processing) and the result runs lightning fast.