postgresql-unit icon indicating copy to clipboard operation
postgresql-unit copied to clipboard

Sane way to convert a double to a unit

Open narrowtux opened this issue 5 years ago • 3 comments

Right now, the only working way to convert a double precision value you know the unit of into a value of the type unit is concat(23.5, '°C')::unit which is a bit clunky.

I tried 23.5 * '°C'::unit but this does not work with units with offsets (such as celsius) as this would return the incorrect amount 23.5 K.

I'd imagine a function like at_unit(double precision, unit) which might be able to do the job more efficiently instead of converting a double to string and back again.

narrowtux avatar Jun 26 '19 12:06 narrowtux

The generic way for non-shifted units would be multiplication. At the moment there's only two shifted unit supported (°C and °F, the other in definitions.units would be various shoe sizes which I didn't bother importing). For °C, there's a predefined constructor function (like for many of the standard SI units like meter(), ...):

# select celsius(23.5);
 celsius  
──────────
 296.65 K

There's none for °F, and adding a generic one makes sense. The signature will have to be at_unit(double precision, text) though, because anything in "unit" gets converted to base units immediately so the function wouldn't even see any shift.

df7cb avatar Jun 26 '19 13:06 df7cb

Bump. I love this package, but getting 'real-world' data into this domain is tricky.

publicmatt avatar Jun 20 '23 01:06 publicmatt

For any "normal" unit you can use multiplication:

insert into currents values (123.456 * 'mA'::unit);

df7cb avatar Jun 20 '23 09:06 df7cb