Mottie / javascript-number-formatter

Lightweight & Fast JavaScript Number Formatter
http://mottie.github.io/javascript-number-formatter/
MIT License
141 stars 37 forks source link

Different Handling for Negative "-" and Positive "+" Signs #9

Closed hyyan closed 6 years ago

hyyan commented 6 years ago

Hello

Thanks for the great done job with this library, it is really the only stable and solid solution I could find for Javascript and the code is a state of art, easy to follow and well tested.

I would like to propose a different handling for negative and positive signs

The Current behavior

Sign Behavior
- The minus sign reverse the number sign
+ always ignored and omitted from the result

The New Behavior

Sign Behavior
- The minus sign creates a "-" in the result if the number is negative; otherwise ignored
+ The plus sign becomes a "+" in the result if the number is positive, or a "-" if the number is negative.

Examples compares between the new and the old behavior :

Number Mask Old Behavior New Behavior
-5000.123456789 -#,##0.###### 5,000.123457 -5,000.123457
5000.123456789 -#,##0.###### -5,000.123457 5,000.123457
-5000.123456789 #,##0.###### -5,000.123457 5,000.123457
+5000.123456789 +#,##0.###### 5,000.123457 +5,000.123457
+5000.123456789 #,##0.###### 5,000.123457 +5,000.123457
-5000.123456789 +#,##0.###### -5,000.123457 -5,000.123457

The new behavior makes more sense than the old one and it is less confusing. Of course such a change will not be a BC but I believe It’s worth it

I will send a PR for this feature and I hope it will be merged

Mottie commented 6 years ago

I did find one issue in the code, not your additions. I'm not sure why it didn't pop up before; but if you pass a value that's a string, you'll get a JS error. The fix requires this change:

// Fix the decimal first, toFixed will auto fill trailing zero.
value = (+value).toFixed(mask[1] && mask[1].length);

I'll add a test for this in the rewrite.