-1

I'd like to display some integer with currency index (I mean dot and double zero) For example like here:

#include <iostream>

int main() {
    int w1=700,c1=99,c2=98;
    double noh2o=w1*(100.0-c1)/100.0;
    double w2=noh2o+noh2o/(100.0-c2)*c2;
    std::cout<<w2<<std::endl;
}

If somebody can help me I will be thankful.

  • 1
    It's not a good idea to use `double` for this at all, see https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency/3730040#3730040. Better to keep a single integer variable that counts cents, and output `amount / 100` and `amount % 100` separately. – Nate Eldredge Mar 24 '21 at 20:29
  • 1
    If you're talking about `w2`, it already *is* a `double` and should be "output" as such. What is the problem with the code you show? What is the output you get? What is the output you expect? – Some programmer dude Mar 24 '21 at 20:29
  • Do you want the integer `1234` displayed as `1234.00` or as `12.34`? (The output of your program is `350`; that doesn't tell me what you're trying to do.) Does `std::cout << n << ".00"` not meet your requirements? – Keith Thompson Mar 24 '21 at 20:53

2 Answers2

2

You are supposed to do it with the locale library.

Mostly copied from https://en.cppreference.com/w/cpp/io/manip/put_money like so:

#include <iomanip>
#include <iostream>
#include <locale>

int main() {
  long double val = 239.9;
  std::cout.imbue(std::locale("en_US.UTF-8"));
  std::cout << std::showbase
            << "en_US: " << std::put_money(val)
            << std::endl;
  return 0;
}
Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
  • this is a far better answer the one accepted – Alessandro Teruzzi Mar 24 '21 at 21:45
  • The answer is good, but I am sceptical about this feature. It seldom makes sense to have some amount displayed in whichever happens to be the local currency. Something like this could explain why I recently experienced some crazy prices on a major website, nicely displayed in my local currency, but clearly with the amount still in the original currency. – nielsen Mar 24 '21 at 22:31
  • @nielsen yes that would be a problem if the currency value itself didn't get converted. I don't think that we can expect the C++ library to go to the internet for currency values and convert in real-time, yet. :-) – Zan Lynx Mar 24 '21 at 23:54
1

Use std::fixed and std::setprecision.

Try it online!

#include <iostream>
#include <iomanip>

int main() {
    int w1=700,c1=99,c2=98;
    double noh2o=w1*(100.0-c1)/100.0;
    double w2=noh2o+noh2o/(100.0-c2)*c2;
    std::cout << std::fixed << std::setprecision(2) << w2 << std::endl;
}

Output:

350.00
Arty
  • 14,883
  • 6
  • 36
  • 69