unitsofmeasurement / indriya

JSR 385 - Reference Implementation
Other
115 stars 40 forks source link

Quantities#getQuantity(CharSequence) doesn't work with Dimensionless quantities #324

Closed daniel-shuy closed 3 years ago

daniel-shuy commented 3 years ago

According to the Javadoc of Quantities#getQuantity(CharSequence):

This method can be used to parse dimensionless quantities. Quantity proportion = Quantities.getQuantity("0.234").asType(Dimensionless.class);

However, running Quantities.getQuantity("0.234").asType(Dimensionless.class) throws:

IllegalArgumentException: No Unit found
andi-huber commented 3 years ago

confirmed;

Instead of using parsing, you could also write

import tech.units.indriya.AbstractUnit;
...
Quantity<Dimensionless> q = Quantities.getQuantity(0.234, AbstractUnit.ONE); 
keilw commented 3 years ago

@andi-huber Not sure if that's even a bug, the statement is completely correct, it's a number, not a quantity.

andi-huber commented 3 years ago

Hi @keilw - what do you mean, which statement is correct?

keilw commented 3 years ago

The IllegalArgumentException is correct, I see nothing wrong if you try to create a quantity without a unit there's an error. If it's not documented in the JavaDoc we might like to change that.

andi-huber commented 3 years ago

Ok, I'm agnostic to how we want to solve this, fixing code or fixing java-doc, both fine with me.

daniel-shuy commented 3 years ago

If the behavior is correct, then ideally the Javadoc should be updated to recommend using AbstractQuantity#parse(CharSequence) to parse dimensionless quantities

keilw commented 3 years ago

It is correct because Quantities also should allow to parse mixed quantities. There is no bug, merely an inconsistency between the two because they use exactly the same SimpleUnitFormat except configured differently. While #325 is a true bug, @andi-huber would you like to take care of that?

keilw commented 3 years ago

It was as I thought, while Quantities.getQuantity("1 m 70 cm") works perfectly fine and converts to a sum of a MixedQuantity, calling AbstractQuantity.parse("1 m 70 cm") fails with a MeasurementParseException. Since AbstractQuantity and MixedQuantity do not have the same parent for a good reason (MixedQuantity is more of a specialized Collection or array) we could leave it like that allowing the number without a unit to be parsed only by AbstractQuantity while Quantities recognizes mixed strings but it insists on a unit for that reason.

daniel-shuy commented 3 years ago

Thanks @keilw