1

I want to subtract from this number and make the output in string, but I want to remove these zeros

When I print the number in float, these zeros disappear.

int main(){

    string money = "5000";

    float r = atof(money.c_str()) - 1000;
    cout << r << endl;
    cout << to_string(r);


    return 0;
}

this is the output:

4000
4000.000000
Raafat
  • 49
  • 8
  • Floating point numbers are imprecise. What looks to you like 5000 is often represented internally as 5000.00000000972 or similar. `operator<<` rounded off the extra garbage for you, but it looks like `to_string` wasn't as smart. Side note: Money is often better handled in integers with the smallest possible increment (pennies for example) as the basic unit. This prevents floating point errors. – user4581301 Jul 11 '19 at 19:28
  • That's a good dupe, but it doesn't address how to get around this problem. If you want `cout`-like behaviour, [use an `ostringstream`](https://en.cppreference.com/w/cpp/io/basic_ostringstream) to get it: `string my_to_string(float r) { ostringstream fmt; fmt << r; return fmt.str(); }` Not that this is not ideal. Floating point numbers are imprecise ([Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken)), and this imprecision can lead to other errors. – user4581301 Jul 11 '19 at 20:00

0 Answers0