gentooboontoo / js-quantities

JavaScript library for quantity calculation and unit conversion
http://gentooboontoo.github.io/js-quantities/
MIT License
396 stars 102 forks source link

ml and cc^3 are not being simplified #76

Closed luzlab closed 7 years ago

luzlab commented 7 years ago

js-quantities doesn't simplify ml and cm^3 corrently when doing math.

var w = Qty('1 g');
var v = Qty('1 cm^3');
var density = w.div(v);
var sample_v = Qty('100 ml');
var sample_w = sample_v.mul(density);
sample_w.toString() // returns '100 ml*g/cm3', instead of '100 g'

js-quantities does recognize ml and cm^3 as the same unit however...

var q1 = Qty('1 cm^3');
var q2 = Qty('1 ml');
q1.eq(q2); // return true
rage-shadowman commented 7 years ago

Doesn't the unit "ml" mean "milli-liter" (volume)? And "cm" mean "centi-meter" (length)? Volume and length are not equivalent unit types. The "eq" function should throw an incompatible unit error.

Duh... Never-mind... "cm^3" (volume), not "cm" (length).

rage-shadowman commented 7 years ago

Ok, I see what you're doing here. The issue is just that things aren't simplified in the text representation, since the "g/cm^3" is not compatible with "ml". If you instead did:

var simplifiedVolume = v.to(sample_v);
var density = w.div(simplifiedVolume);
sample_w = sample_v.mul(density)

...it would simplify?

luzlab commented 7 years ago

Thanks for that explanation. So we should just cast the units manually rather relying on automatic simplification... So are units (or prefixes) ever simplified automatically?

Do you think this would work?

// same setup as before...
var w = Qty('1 g');
var v = Qty('1 cm^3');
var density = w.div(v);
var sample_v = Qty('100 ml');
var sample_w = sample_v.mul(density);
sample_w.toString() // returns '100 ml*g/cm^3'

// would this work?
sample_w.toString('g') // expect to return '100 g'?

I'll try this next time I work with on this part of my project.

rage-shadowman commented 7 years ago

or maybe (if you already know you are looking at a result in units of "g"):

var result_in_g = sample_w.to("g");
result_in_g.toString();

,,,but yes, it looks like he added the option for target units in the toString function, so ignore my above.

luzlab commented 7 years ago

So Qty does properly simplify/convert between 'ml' and 'cm^3'.

Qty('100 ml*g/cm^3').toString('g')  // returns 100g