globalize icon indicating copy to clipboard operation
globalize copied to clipboard

parseInt and parseFloat fail (NaN) with negative currency

Open rdworth opened this issue 15 years ago • 5 comments

// Expected Globalize.parseInt( Globalize.format(-3.91, "c") ); // -3 Globalize.parseFloat( Globalize.format(-3.91, "c") ); // -3.91

// Actual Globalize.parseInt( Globalize.format(-3.91, "c") ); // NaN Globalize.parseFloat( Globalize.format(-3.91, "c") ); // NaN

The expected values are returned if the original value is positive rather than negative.

rdworth avatar Jun 22 '11 15:06 rdworth

As far as I can see, parsing negative currencies works for most locales. For the "en" locale, I get NaN in the sample case posted for parseFloat but 0 for parseInt. I guess the reason is that parseInt just calls parseFloat and truncate with the definition truncate = function( value ) { return value | 0; };

Anyway, the basic reason is apparently that the code has no provisions for parsing the negative currency pattern "($n)". As far as I can see, a currency is parsed simply by removing the currency symbol and then parsing as a number. This fails when a currency pattern structurally differs from the number pattern.

yucca42 avatar Jun 25 '11 10:06 yucca42

This issue can be closed, fixed here: https://github.com/jquery/globalize/commit/858f4904a0a8330d488c587c193efa2804b9b99b

kflorence avatar Aug 01 '11 20:08 kflorence

I believe the fundamental issue still exists. The fix reference by kflorence works for 'en' where the negative currency pattern is '($n)'. However, when parsing a negative currency for 'pt-BR', NaN is still returned. The negative number pattern for 'pt-BR' is '-n', while the negative currency pattern is '-R$ n'. Just like yucca42 mentioned, the parsing code never uses the negative currency pattern if the string is a currency. Only the negative number pattern is used.

cprokopiak avatar Sep 20 '11 18:09 cprokopiak

The issue is caused by the parse function if the negative sign in in front of the currency sign and there is a space between the currency sign.

It tries to parse '- 123' which fails.

Fix committed and pull request issued: https://github.com/jquery/globalize/pull/126

seanzx85 avatar Oct 16 '12 18:10 seanzx85

Fixed, thanks @SeanZX85

jzaefferer avatar Oct 16 '12 18:10 jzaefferer