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

added ability to drop units on toString #10

Open EntilZha opened 10 years ago

EntilZha commented 10 years ago

I have been working js quantities into an application I am developing and ran into wanting being able to use toString to return only the scalar and not the number. My specific use case is to convert it to a different unit and assign a precision (in my case of 1 position). I don't want the unit text though (using degree symbol).

I went ahead and added another parameter for the toString number which if left out should default to failing the false check. I have not written any tests, but would be open to writing some if it seems that my proposed addition would get merged in.

Hopefully I am going about this right, haven't done very many pull requests so far.

gentooboontoo commented 10 years ago

Hi @EntilZha,

Thank you very much for your PR.

Before you open this issue, I have already made an experimental branch (qty-formatter) allowing custom formatting of quantities by defining a default global formatter or passing a specific one to #toString() method:

var formatter = function(scalar, units) {
  return scalar.toString();
}
Qty.formatter = formatter:
// Or
qty.toString(formatter);

Could you try it and tell me if it could suit you (gentooboontoo/js-quantities@qty-formatter) ? If so, I could merge it into master and make a new release.

For the doc, see: https://github.com/gentooboontoo/js-quantities/tree/qty-formatter#formatting-quantities

EntilZha commented 10 years ago

How would a formatter look if you wanted to use the already built in rounding and simply wanted to use the toString for the formatter on the scalar (ie return scalar.toString() as above)? I haven't tested it yet, but it seems like scalar.toString would return it not rounded. Looking at the docs, it uses a custom rounding function as an example, I was just curious if there was a way to call the already built in rounding function, then return toString on that quantity.

EDIT: I browsed through the code in the branch, it seems like the rounding function that is in the main branch that is documented here:

qty.toString(target_units, max_decimals);

and has a few other calls, has been replaced with a toString method that does: (scalar +" " + units).trim()

Perhaps you could combine the current toString method in master with the formatter branch and include it as the defaultFormatter. It would include a lot of default functionality that I find quite useful already. I haven't looked into it much so far, but perhaps you could use argument unpacking for the formatter to allow a variable number of arguments, but always expect at least scalar and units?