Project

General

Profile

$xx,xxx.xx - what’s a good way to get this format (+ international)

Added by Mark Travis 2 months ago

I’ve got a number of WTableViews that use WStandardItemModels and use WItemDelegate to set the format to “%.2f” (or .3f, etc.)

I need to format a few tables as nicely formatted currency, such as $45,876.34 or 45.876,99€ or what have you.

I figured out a way to do it with the fmt library. I didn’t see anything in the Wt::Payment libraries.

Before I go down the road of trying to create a custom WItemDelegate that uses fmt, am I missing something obvious?


Replies (2)

RE: $xx,xxx.xx - what’s a good way to get this format (+ international) - Added by Mark Travis 2 months ago

I figured it out. It uses the printf formatting standard found here: https://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html
For now, I got it to work using:

 delegate->setTextFormat("$%'.2f");

I'm still looking for a way to get the currency symbol to show up. For now I've hardcoded it.

RE: $xx,xxx.xx - what’s a good way to get this format (+ international) - Added by Matthias Van Ceulebroeck about 2 months ago

Hey Mark,

I believe there are two ways to achieve this:

  • a custom delegate that changes the text itself
  • a custom type that defines an Wt::asString. You would achieve this by doing:
namespace Wt {
  template<>
  struct any_traits<Money> {
    static WString asString(const Money& money, const WString& format)
    {
      return // formatted string
    }
  };

As a P.S. you can use a utility like a stringstream, imbue it with your locale, and std::put_money (from iomanip) on it. That way you can make the fomratting always consistent with the locale you define. You can retrieve the money abbreviation or symbol from std::use_facet.
This may be handy if you are working across multiple locales with different conventions.

    (1-2/2)