Shopify / measured

Encapsulate measurements and their units in Ruby and Ruby on Rails.
MIT License
337 stars 28 forks source link

Rounding and measured #96

Closed javierhonduco closed 6 years ago

javierhonduco commented 6 years ago

:wave:

@alexgomez54 and I have bumped into the use case of representing a value and its unit as a string (like in Measured#to_s's spirit`) but specifying some rounding.

Usually, our code looks like:

def weight_with_decimals(decimals = 2)
  rounded_value = weight.value.round(decimals)  # weight.is_a?(Measured::Weight) => true
  Measured::Weight.new(rounded_value, weight.unit).to_s
end

We were wondering if it would make sense to have a feature that does something like that, in a more generic way, inside of Measured 😄 .

What do you think @thegedge @kmcphillips @benwah? 😀

benwah commented 6 years ago

I think it would be a useful feature, perhaps a Measured::Weight / Measured::Length could have a round method, which would return a new instance?

thegedge commented 6 years ago

My only concern here is that you have to be very aware of the underlying unit for round to be significant. For example, think about let's say a = 1g and b = 0.001kg . Now we have a == b but a.round(2) != b.round(2) which feels like kind of a weird property to introduce.

Is the use of this generally for presentation?

javierhonduco commented 6 years ago

Good call, that's an important point!

Yeah, it's for presentation on my side and would say on @alexgomez54' side too

thegedge commented 6 years ago

If it's mostly presentation, I would consider looking at how we could incorporate it into measured-rails. We could also consider a way of configuring a unit system for the precision used when to_s-ing. I'd lean more towards that than a round function, for the reason in my previous comment :)

javierhonduco commented 6 years ago

It's indeed presentation-only.

Cool, will have a look at how to implement this :)

javierhonduco commented 6 years ago

Closed with #99