How to print prefixed unit without changing base unit?

36 views Asked by At

If I define a value in bytes and print it:

using namespace boost::units;
using namespace boost::units::information;
quantity<info> nbytes = 1234 * bytes;
std::cout << nbytes << std::endl; // 1234 B

Ok, that's fine, but what I really want is "1.234 kB". There's an auto-scaling prefix for that:

std::cout << engineering_prefix << nbytes << std::endl; // 9.872 kb

It printed in units of the base unit, bits. How can I get it to auto-scale, but preserve the base unit of bytes?

1

There are 1 answers

0
John Freeman On

One way (the only way I've found so far) is to define my own base unit that does not scale down to bits. It appears the implementation of do_print_prefixed deep in the bowels of Boost.Unit unscales the value and there is no way to stop it.

struct byte_unit
    : public boost::units::base_unit<byte_unit, boost::units::information_dimension, 1>
{};
using storage = boost::units::make_system<byte_unit>::type;
using byte = boost::units::unit<boost::units::information_dimension, storage>;

BOOST_UNITS_STATIC_CONSTANT(bytes, byte);

namespace boost {
namespace units {

template <>
struct base_unit_info<ripple::CommunicationMeter::byte_unit>
{
    static BOOST_CONSTEXPR const char* name() { return ("byte"); }
    static BOOST_CONSTEXPR const char* symbol() { return ("B"); }
};

}  // namespace units
}  // namespace boost