Boost logo

Boost Users :

Subject: Re: [Boost-users] boost.units converting double tp SI prefix
From: Paul A. Bristow (pbristow_at_[hidden])
Date: 2010-03-13 17:52:35


> -----Original Message-----
> From: boost-users-bounces_at_[hidden] [mailto:boost-users-bounces_at_[hidden]]
> On Behalf Of Steven Watanabe
> Sent: Friday, March 12, 2010 7:23 PM
> To: boost-users_at_[hidden]
> Subject: Re: [Boost-users] boost.units converting double tp SI prefix
>
> AMDG
>
> Olaf Peter wrote:
> > is there a way to use boost.units to convert a double automatically to a
> > SI unit prefix, e.g. 10e-3 to 10m or 10e3 to 10k ?? The value isn't know
> > at compile time, so the decision has to be done on runtime.
> >
>
> There is not such a facility. There will soon be support for
> printing things like 1.0 km instead of 1000 m, but formatting
> of raw numbers is somewhat beyond the scope of the library.

But I think that you can create your own unit (and quantity) easily,
and then you *can* use the very useful auto prefixing system Steven has devised.

For example for show this, I've created a entirely useless 'thing' type - dimensionless of course.

It could be widget count, (or indeed a unit of currency) with a name and symbol.

struct thing_base_unit : boost::units::base_unit<thing_base_unit, boost::units::dimensionless_type, 4>
{
  static const char* name() { return("thing"); }
  static const char* symbol() { return(""); }
};

and this constructs a quantity of it (2048.0 - a double by default)

  quantity<thing_base_unit::unit_type> t = 2048. * thing_base_unit::unit_type();

and you can then chose to output with a trailing name of your choice

   cout << name_format << engineering_prefix << t << endl; // 2.048 kilothing

and similarly with a symbol (I've defined my symbol to be a "", so I just get the SI prefix.

   cout << symbol_format << engineering_prefix << t << endl; // 2.048 k

Steven has even more cunningly allowed the binary 2^10, 2^20, 2^30 ... prefixes,
 
   cout << binary_prefix << t << endl; // "2 Ki"

For currency, the multiple (k, M, G) *must precede* the name or symbol of the unit.

(*not* Symbol first as one might really want for $, £ € ...)

quantity<euro_base_unit::unit_type> ce = 2048. * euro_base_unit::unit_type();

  cout << name_format << engineering_prefix << ce << endl; // 2.048 kiloEUR

  cout << symbol_format << engineering_prefix << ce << endl; // 2.048 k€

Perhaps this will meet your needs when available?

Paul

---
Paul A. Bristow
Prizet Farmhouse
Kendal, UK   LA8 8AB
+44 1539 561830, mobile +44 7714330204
pbristow_at_[hidden]

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net