df7cb / postgresql-unit

SI Units for PostgreSQL
262 stars 12 forks source link

Sane way to convert a double to a unit #24

Open narrowtux opened 5 years ago

narrowtux commented 5 years ago

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.

df7cb commented 5 years ago

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.

publicmatt commented 1 year ago

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

df7cb commented 1 year ago

For any "normal" unit you can use multiplication:

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