• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /********************************************************************
4  * COPYRIGHT:
5  * Copyright (c) 1997-2016, International Business Machines Corporation and
6  * others. All Rights Reserved.
7  ********************************************************************/
8 /********************************************************************************
9 *
10 * File CNUMTST.C
11 *
12 *     Madhu Katragadda              Creation
13 *
14 * Modification History:
15 *
16 *   Date        Name        Description
17 *   06/24/99    helena      Integrated Alan's NF enhancements and Java2 bug fixes
18 *   07/15/99    helena      Ported to HPUX 10/11 CC.
19 *********************************************************************************
20 */
21 
22 /* C API TEST FOR NUMBER FORMAT */
23 
24 #include "unicode/utypes.h"
25 
26 #if !UCONFIG_NO_FORMATTING
27 
28 #include "unicode/uloc.h"
29 #include "unicode/umisc.h"
30 #include "unicode/unum.h"
31 #include "unicode/unumsys.h"
32 #include "unicode/ustring.h"
33 #include "unicode/udisplaycontext.h"
34 
35 #include "cintltst.h"
36 #include "cnumtst.h"
37 #include "cmemory.h"
38 #include "cstring.h"
39 #include "putilimp.h"
40 #include "uassert.h"
41 #include <stdbool.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 
tagAssert(const char * f,int32_t l,const char * msg)45 static const char *tagAssert(const char *f, int32_t l, const char *msg) {
46     static char _fileline[1000];
47     sprintf(_fileline, "%s:%d: ASSERT_TRUE(%s)", f, l, msg);
48     return _fileline;
49 }
50 
51 #define ASSERT_TRUE(x)   assertTrue(tagAssert(__FILE__, __LINE__, #x), (x))
52 
53 void addNumForTest(TestNode** root);
54 static void TestTextAttributeCrash(void);
55 static void TestNBSPInPattern(void);
56 static void TestInt64Parse(void);
57 static void TestParseCurrency(void);
58 static void TestMaxInt(void);
59 static void TestNoExponent(void);
60 static void TestSignAlwaysShown(void);
61 static void TestMinimumGroupingDigits(void);
62 static void TestParseCaseSensitive(void);
63 static void TestUFormattable(void);
64 static void TestUNumberingSystem(void);
65 static void TestCurrencyIsoPluralFormat(void);
66 static void TestContext(void);
67 static void TestCurrencyUsage(void);
68 static void TestCurrFmtNegSameAsPositive(void);
69 static void TestVariousStylesAndAttributes(void);
70 static void TestParseCurrPatternWithDecStyle(void);
71 static void TestFormatForFields(void);
72 static void TestRBNFRounding(void);
73 static void Test12052_NullPointer(void);
74 static void TestParseCases(void);
75 static void TestSetMaxFracAndRoundIncr(void);
76 static void TestIgnorePadding(void);
77 static void TestSciNotationMaxFracCap(void);
78 static void TestMinIntMinFracZero(void);
79 static void Test21479_ExactCurrency(void);
80 static void Test22088_Ethiopic(void);
81 static void TestParseWithEmptyCurr(void);
82 
83 #define TESTCASE(x) addTest(root, &x, "tsformat/cnumtst/" #x)
84 
addNumForTest(TestNode ** root)85 void addNumForTest(TestNode** root)
86 {
87     TESTCASE(TestNumberFormat);
88     TESTCASE(TestSpelloutNumberParse);
89     TESTCASE(TestSignificantDigits);
90     TESTCASE(TestSigDigRounding);
91     TESTCASE(TestNumberFormatPadding);
92     TESTCASE(TestInt64Format);
93     TESTCASE(TestNonExistentCurrency);
94     TESTCASE(TestCurrencyRegression);
95     TESTCASE(TestTextAttributeCrash);
96     TESTCASE(TestRBNFFormat);
97     TESTCASE(TestRBNFRounding);
98     TESTCASE(TestNBSPInPattern);
99     TESTCASE(TestInt64Parse);
100     TESTCASE(TestParseZero);
101     TESTCASE(TestParseCurrency);
102     TESTCASE(TestCloneWithRBNF);
103     TESTCASE(TestMaxInt);
104     TESTCASE(TestNoExponent);
105     TESTCASE(TestSignAlwaysShown);
106     TESTCASE(TestMinimumGroupingDigits);
107     TESTCASE(TestParseCaseSensitive);
108     TESTCASE(TestUFormattable);
109     TESTCASE(TestUNumberingSystem);
110     TESTCASE(TestCurrencyIsoPluralFormat);
111     TESTCASE(TestContext);
112     TESTCASE(TestCurrencyUsage);
113     TESTCASE(TestCurrFmtNegSameAsPositive);
114     TESTCASE(TestVariousStylesAndAttributes);
115     TESTCASE(TestParseCurrPatternWithDecStyle);
116     TESTCASE(TestFormatForFields);
117     TESTCASE(Test12052_NullPointer);
118     TESTCASE(TestParseCases);
119     TESTCASE(TestSetMaxFracAndRoundIncr);
120     TESTCASE(TestIgnorePadding);
121     TESTCASE(TestSciNotationMaxFracCap);
122     TESTCASE(TestMinIntMinFracZero);
123     TESTCASE(Test21479_ExactCurrency);
124     TESTCASE(Test22088_Ethiopic);
125     TESTCASE(TestParseWithEmptyCurr);
126 }
127 
128 /* test Parse int 64 */
129 
TestInt64Parse()130 static void TestInt64Parse()
131 {
132 
133     UErrorCode st = U_ZERO_ERROR;
134     UErrorCode* status = &st;
135 
136     const char* st1 = "009223372036854775808";
137     const int size = 21;
138     UChar text[21];
139 
140 
141     UNumberFormat* nf;
142 
143     int64_t a;
144 
145     u_charsToUChars(st1, text, size);
146     nf = unum_open(UNUM_DEFAULT, NULL, -1, NULL, NULL, status);
147 
148     if(U_FAILURE(*status))
149     {
150         log_data_err("Error in unum_open() %s \n", myErrorName(*status));
151         return;
152     }
153 
154     log_verbose("About to test unum_parseInt64() with out of range number\n");
155 
156     a = unum_parseInt64(nf, text, size, 0, status);
157     (void)a;     /* Suppress set but not used warning. */
158 
159 
160     if(!U_FAILURE(*status))
161     {
162         log_err("Error in unum_parseInt64(): %s \n", myErrorName(*status));
163     }
164     else
165     {
166         log_verbose("unum_parseInt64() successful\n");
167     }
168 
169     unum_close(nf);
170     return;
171 }
172 
173 /* test Number Format API */
TestNumberFormat()174 static void TestNumberFormat()
175 {
176     UChar *result=NULL;
177     UChar temp1[512];
178     UChar temp2[512];
179 
180     UChar temp[5];
181 
182     UChar prefix[5];
183     UChar suffix[5];
184     UChar symbol[20];
185     int32_t resultlength;
186     int32_t resultlengthneeded;
187     int32_t parsepos;
188     double d1 = -1.0;
189     int32_t l1;
190     double d = -10456.37;
191     double a = 1234.56, a1 = 1235.0;
192     int32_t l = 100000000;
193     UFieldPosition pos1;
194     UFieldPosition pos2;
195     int32_t numlocales;
196     int32_t i;
197 
198     UNumberFormatAttribute attr;
199     UNumberFormatSymbol symType = UNUM_DECIMAL_SEPARATOR_SYMBOL;
200     int32_t newvalue;
201     UErrorCode status=U_ZERO_ERROR;
202     UNumberFormatStyle style= UNUM_DEFAULT;
203     UNumberFormat *pattern;
204     UNumberFormat *def, *fr, *cur_def, *cur_fr, *per_def, *per_fr,
205                   *cur_frpattern, *myclone, *spellout_def;
206 
207     /* Testing unum_open() with various Numberformat styles and locales*/
208     status = U_ZERO_ERROR;
209     log_verbose("Testing  unum_open() with default style and locale\n");
210     def=unum_open(style, NULL,0,NULL, NULL,&status);
211 
212     /* Might as well pack it in now if we can't even get a default NumberFormat... */
213     if(U_FAILURE(status))
214     {
215         log_data_err("Error in creating default NumberFormat using unum_open(): %s (Are you missing data?)\n", myErrorName(status));
216         return;
217     }
218 
219     log_verbose("\nTesting unum_open() with french locale and default style(decimal)\n");
220     fr=unum_open(style,NULL,0, "fr_FR",NULL, &status);
221     if(U_FAILURE(status))
222         log_err("Error: could not create NumberFormat (french): %s\n", myErrorName(status));
223 
224     log_verbose("\nTesting unum_open(currency,NULL,status)\n");
225     style=UNUM_CURRENCY;
226     /* Can't hardcode the result to assume the default locale is "en_US". */
227     cur_def=unum_open(style, NULL,0,"en_US", NULL, &status);
228     if(U_FAILURE(status))
229         log_err("Error: could not create NumberFormat using \n unum_open(currency, NULL, &status) %s\n",
230                         myErrorName(status) );
231 
232     log_verbose("\nTesting unum_open(currency, frenchlocale, status)\n");
233     cur_fr=unum_open(style,NULL,0, "fr_FR", NULL, &status);
234     if(U_FAILURE(status))
235         log_err("Error: could not create NumberFormat using unum_open(currency, french, &status): %s\n",
236                 myErrorName(status));
237 
238     log_verbose("\nTesting unum_open(percent, NULL, status)\n");
239     style=UNUM_PERCENT;
240     per_def=unum_open(style,NULL,0, NULL,NULL, &status);
241     if(U_FAILURE(status))
242         log_err("Error: could not create NumberFormat using unum_open(percent, NULL, &status): %s\n", myErrorName(status));
243 
244     log_verbose("\nTesting unum_open(percent,frenchlocale, status)\n");
245     per_fr=unum_open(style, NULL,0,"fr_FR", NULL,&status);
246     if(U_FAILURE(status))
247         log_err("Error: could not create NumberFormat using unum_open(percent, french, &status): %s\n", myErrorName(status));
248 
249     log_verbose("\nTesting unum_open(spellout, NULL, status)");
250     style=UNUM_SPELLOUT;
251     spellout_def=unum_open(style, NULL, 0, "en_US", NULL, &status);
252     if(U_FAILURE(status))
253         log_err("Error: could not create NumberFormat using unum_open(spellout, NULL, &status): %s\n", myErrorName(status));
254 
255     /* Testing unum_clone(..) */
256     log_verbose("\nTesting unum_clone(fmt, status)");
257     status = U_ZERO_ERROR;
258     myclone = unum_clone(def,&status);
259     if(U_FAILURE(status))
260         log_err("Error: could not clone unum_clone(def, &status): %s\n", myErrorName(status));
261     else
262     {
263         log_verbose("unum_clone() successful\n");
264     }
265 
266     /*Testing unum_getAvailable() and unum_countAvailable()*/
267     log_verbose("\nTesting getAvailableLocales and countAvailable()\n");
268     numlocales=unum_countAvailable();
269     if(numlocales < 0)
270         log_err("error in countAvailable");
271     else{
272         log_verbose("unum_countAvailable() successful\n");
273         log_verbose("The no: of locales where number formatting is applicable is %d\n", numlocales);
274     }
275     for(i=0;i<numlocales;i++)
276     {
277         log_verbose("%s\n", unum_getAvailable(i));
278         if (unum_getAvailable(i) == 0)
279             log_err("No locale for which number formatting patterns are applicable\n");
280         else
281             log_verbose("A locale %s for which number formatting patterns are applicable\n",unum_getAvailable(i));
282     }
283 
284 
285     /*Testing unum_format() and unum_formatdouble()*/
286     u_uastrcpy(temp1, "$100,000,000.00");
287 
288     log_verbose("\nTesting unum_format() \n");
289     resultlength=0;
290     pos1.field = UNUM_INTEGER_FIELD;
291     resultlengthneeded=unum_format(cur_def, l, NULL, resultlength, &pos1, &status);
292     if(status==U_BUFFER_OVERFLOW_ERROR)
293     {
294         status=U_ZERO_ERROR;
295         resultlength=resultlengthneeded+1;
296         result=(UChar*)malloc(sizeof(UChar) * resultlength);
297 /*        for (i = 0; i < 100000; i++) */
298         {
299             unum_format(cur_def, l, result, resultlength, &pos1, &status);
300         }
301     }
302 
303     if(U_FAILURE(status))
304     {
305         log_err("Error in formatting using unum_format(.....): %s\n", myErrorName(status) );
306     }
307     if(u_strcmp(result, temp1)==0)
308         log_verbose("Pass: Number formatting using unum_format() successful\n");
309     else
310         log_err("Fail: Error in number Formatting using unum_format()\n");
311     if(pos1.beginIndex == 1 && pos1.endIndex == 12)
312         log_verbose("Pass: Complete number formatting using unum_format() successful\n");
313     else
314         log_err("Fail: Error in complete number Formatting using unum_format()\nGot: b=%d end=%d\nExpected: b=1 end=12\n",
315                 pos1.beginIndex, pos1.endIndex);
316 
317     free(result);
318     result = 0;
319 
320     log_verbose("\nTesting unum_formatDouble()\n");
321     u_uastrcpy(temp1, "-$10,456.37");
322     resultlength=0;
323     pos2.field = UNUM_FRACTION_FIELD;
324     resultlengthneeded=unum_formatDouble(cur_def, d, NULL, resultlength, &pos2, &status);
325     if(status==U_BUFFER_OVERFLOW_ERROR)
326     {
327         status=U_ZERO_ERROR;
328         resultlength=resultlengthneeded+1;
329         result=(UChar*)malloc(sizeof(UChar) * resultlength);
330 /*        for (i = 0; i < 100000; i++) */
331         {
332             unum_formatDouble(cur_def, d, result, resultlength, &pos2, &status);
333         }
334     }
335     if(U_FAILURE(status))
336     {
337         log_err("Error in formatting using unum_formatDouble(.....): %s\n", myErrorName(status));
338     }
339     if(result && u_strcmp(result, temp1)==0)
340         log_verbose("Pass: Number Formatting using unum_formatDouble() Successful\n");
341     else {
342       log_err("FAIL: Error in number formatting using unum_formatDouble() - got '%s' expected '%s'\n",
343               aescstrdup(result, -1), aescstrdup(temp1, -1));
344     }
345     if(pos2.beginIndex == 9 && pos2.endIndex == 11)
346         log_verbose("Pass: Complete number formatting using unum_format() successful\n");
347     else
348         log_err("Fail: Error in complete number Formatting using unum_formatDouble()\nGot: b=%d end=%d\nExpected: b=9 end=11",
349                 pos1.beginIndex, pos1.endIndex);
350 
351 
352     /* Testing unum_parse() and unum_parseDouble() */
353     log_verbose("\nTesting unum_parseDouble()\n");
354 /*    for (i = 0; i < 100000; i++)*/
355     parsepos=0;
356     if (result != NULL) {
357       d1=unum_parseDouble(cur_def, result, u_strlen(result), &parsepos, &status);
358     } else {
359       log_err("result is NULL\n");
360     }
361     if(U_FAILURE(status)) {
362       log_err("parse of '%s' failed. Parsepos=%d. The error is  : %s\n", aescstrdup(result,u_strlen(result)),parsepos, myErrorName(status));
363     }
364 
365     if(d1!=d)
366         log_err("Fail: Error in parsing\n");
367     else
368         log_verbose("Pass: parsing successful\n");
369     if (result)
370         free(result);
371     result = 0;
372 
373     status = U_ZERO_ERROR;
374     /* Testing unum_formatDoubleCurrency / unum_parseDoubleCurrency */
375     log_verbose("\nTesting unum_formatDoubleCurrency\n");
376     u_uastrcpy(temp1, "Y1,235");
377     temp1[0] = 0xA5; /* Yen sign */
378     u_uastrcpy(temp, "JPY");
379     resultlength=0;
380     pos2.field = UNUM_INTEGER_FIELD;
381     resultlengthneeded=unum_formatDoubleCurrency(cur_def, a, temp, NULL, resultlength, &pos2, &status);
382     if (status==U_BUFFER_OVERFLOW_ERROR) {
383         status=U_ZERO_ERROR;
384         resultlength=resultlengthneeded+1;
385         result=(UChar*)malloc(sizeof(UChar) * resultlength);
386         unum_formatDoubleCurrency(cur_def, a, temp, result, resultlength, &pos2, &status);
387     }
388     if (U_FAILURE(status)) {
389         log_err("Error in formatting using unum_formatDoubleCurrency(.....): %s\n", myErrorName(status));
390     }
391     if (result && u_strcmp(result, temp1)==0) {
392         log_verbose("Pass: Number Formatting using unum_formatDoubleCurrency() Successful\n");
393     } else {
394         log_err("FAIL: Error in number formatting using unum_formatDoubleCurrency() - got '%s' expected '%s'\n",
395                 aescstrdup(result, -1), aescstrdup(temp1, -1));
396     }
397     if (pos2.beginIndex == 1 && pos2.endIndex == 6) {
398         log_verbose("Pass: Complete number formatting using unum_format() successful\n");
399     } else {
400         log_err("Fail: Error in complete number Formatting using unum_formatDouble()\nGot: b=%d end=%d\nExpected: b=1 end=6\n",
401                 pos1.beginIndex, pos1.endIndex);
402     }
403 
404     log_verbose("\nTesting unum_parseDoubleCurrency\n");
405     parsepos=0;
406     if (result == NULL) {
407         log_err("result is NULL\n");
408     }
409     else {
410         d1=unum_parseDoubleCurrency(cur_def, result, u_strlen(result), &parsepos, temp2, &status);
411         if (U_FAILURE(status)) {
412           log_err("parseDoubleCurrency '%s' failed. The error is  : %s\n", aescstrdup(result, u_strlen(result)), myErrorName(status));
413         }
414         /* Note: a==1234.56, but on parse expect a1=1235.0 */
415         if (d1!=a1) {
416             log_err("Fail: Error in parsing currency, got %f, expected %f\n", d1, a1);
417         } else {
418             log_verbose("Pass: parsed currency amount successfully\n");
419         }
420         if (u_strcmp(temp2, temp)==0) {
421             log_verbose("Pass: parsed correct currency\n");
422         } else {
423             log_err("Fail: parsed incorrect currency\n");
424         }
425     }
426     status = U_ZERO_ERROR; /* reset */
427 
428     free(result);
429     result = 0;
430 
431 
432 /* performance testing */
433     u_uastrcpy(temp1, "$462.12345");
434     resultlength=u_strlen(temp1);
435 /*    for (i = 0; i < 100000; i++) */
436     {
437         parsepos=0;
438         d1=unum_parseDouble(cur_def, temp1, resultlength, &parsepos, &status);
439     }
440     if(U_FAILURE(status))
441     {
442         log_err("parseDouble('%s') failed. The error is  : %s\n", aescstrdup(temp1, resultlength), myErrorName(status));
443     }
444 
445     /*
446      * Note: "for strict standard conformance all operations and constants are now supposed to be
447               evaluated in precision of long double".  So,  we assign a1 before comparing to a double. Bug #7932.
448      */
449     a1 = 462.12345;
450 
451     if(d1!=a1)
452         log_err("Fail: Error in parsing\n");
453     else
454         log_verbose("Pass: parsing successful\n");
455 
456 free(result);
457 
458     u_uastrcpy(temp1, "($10,456.3E1])");
459     parsepos=0;
460     d1=unum_parseDouble(cur_def, temp1, u_strlen(temp1), &parsepos, &status);
461     if(U_SUCCESS(status))
462     {
463         log_err("Error in unum_parseDouble(..., %s, ...): %s\n", temp1, myErrorName(status));
464     }
465 
466 
467     log_verbose("\nTesting unum_format()\n");
468     status=U_ZERO_ERROR;
469     resultlength=0;
470     parsepos=0;
471     resultlengthneeded=unum_format(per_fr, l, NULL, resultlength, &pos1, &status);
472     if(status==U_BUFFER_OVERFLOW_ERROR)
473     {
474         status=U_ZERO_ERROR;
475         resultlength=resultlengthneeded+1;
476         result=(UChar*)malloc(sizeof(UChar) * resultlength);
477 /*        for (i = 0; i < 100000; i++)*/
478         {
479             unum_format(per_fr, l, result, resultlength, &pos1, &status);
480         }
481     }
482     if(U_FAILURE(status))
483     {
484         log_err("Error in formatting using unum_format(.....): %s\n", myErrorName(status));
485     }
486 
487 
488     log_verbose("\nTesting unum_parse()\n");
489 /*    for (i = 0; i < 100000; i++) */
490     {
491         parsepos=0;
492         l1=unum_parse(per_fr, result, u_strlen(result), &parsepos, &status);
493     }
494     if(U_FAILURE(status))
495     {
496         log_err("parse failed. The error is  : %s\n", myErrorName(status));
497     }
498 
499     if(l1!=l)
500         log_err("Fail: Error in parsing\n");
501     else
502         log_verbose("Pass: parsing successful\n");
503 
504 free(result);
505 
506     /* create a number format using unum_openPattern(....)*/
507     log_verbose("\nTesting unum_openPattern()\n");
508     u_uastrcpy(temp1, "#,##0.0#;(#,##0.0#)");
509     pattern=unum_open(UNUM_IGNORE,temp1, u_strlen(temp1), NULL, NULL,&status);
510     if(U_FAILURE(status))
511     {
512         log_err("error in unum_openPattern(): %s\n", myErrorName(status) );
513     }
514     else
515         log_verbose("Pass: unum_openPattern() works fine\n");
516 
517     /*test for unum_toPattern()*/
518     log_verbose("\nTesting unum_toPattern()\n");
519     resultlength=0;
520     resultlengthneeded=unum_toPattern(pattern, false, NULL, resultlength, &status);
521     if(status==U_BUFFER_OVERFLOW_ERROR)
522     {
523         status=U_ZERO_ERROR;
524         resultlength=resultlengthneeded+1;
525         result=(UChar*)malloc(sizeof(UChar) * resultlength);
526         unum_toPattern(pattern, false, result, resultlength, &status);
527     }
528     if(U_FAILURE(status))
529     {
530         log_err("error in extracting the pattern from UNumberFormat: %s\n", myErrorName(status));
531     }
532     else
533     {
534         if(u_strcmp(result, temp1)!=0)
535             log_err("FAIL: Error in extracting the pattern using unum_toPattern()\n");
536         else
537             log_verbose("Pass: extracted the pattern correctly using unum_toPattern()\n");
538 free(result);
539     }
540 
541     /*Testing unum_getSymbols() and unum_setSymbols()*/
542     log_verbose("\nTesting unum_getSymbols and unum_setSymbols()\n");
543     /*when we try to change the symbols of french to default we need to apply the pattern as well to fetch correct results */
544     resultlength=0;
545     resultlengthneeded=unum_toPattern(cur_def, false, NULL, resultlength, &status);
546     if(status==U_BUFFER_OVERFLOW_ERROR)
547     {
548         status=U_ZERO_ERROR;
549         resultlength=resultlengthneeded+1;
550         result=(UChar*)malloc(sizeof(UChar) * resultlength);
551         unum_toPattern(cur_def, false, result, resultlength, &status);
552     }
553     if(U_FAILURE(status))
554     {
555         log_err("error in extracting the pattern from UNumberFormat: %s\n", myErrorName(status));
556     }
557 
558     status=U_ZERO_ERROR;
559     cur_frpattern=unum_open(UNUM_IGNORE,result, u_strlen(result), "fr_FR",NULL, &status);
560     if(U_FAILURE(status))
561     {
562         log_err("error in unum_openPattern(): %s\n", myErrorName(status));
563     }
564 
565 free(result);
566 
567     /*getting the symbols of cur_def */
568     /*set the symbols of cur_frpattern to cur_def */
569     for (symType = UNUM_DECIMAL_SEPARATOR_SYMBOL; symType < UNUM_FORMAT_SYMBOL_COUNT; symType++) {
570         status=U_ZERO_ERROR;
571         unum_getSymbol(cur_def, symType, temp1, sizeof(temp1), &status);
572         unum_setSymbol(cur_frpattern, symType, temp1, -1, &status);
573         if(U_FAILURE(status))
574         {
575             log_err("Error in get/set symbols: %s\n", myErrorName(status));
576         }
577     }
578 
579     /*format to check the result */
580     resultlength=0;
581     resultlengthneeded=unum_format(cur_def, l, NULL, resultlength, &pos1, &status);
582     if(status==U_BUFFER_OVERFLOW_ERROR)
583     {
584         status=U_ZERO_ERROR;
585         resultlength=resultlengthneeded+1;
586         result=(UChar*)malloc(sizeof(UChar) * resultlength);
587         unum_format(cur_def, l, result, resultlength, &pos1, &status);
588     }
589     if(U_FAILURE(status))
590     {
591         log_err("Error in formatting using unum_format(.....): %s\n", myErrorName(status));
592     }
593 
594     if(U_FAILURE(status)){
595         log_err("Fail: error in unum_setSymbols: %s\n", myErrorName(status));
596     }
597     unum_applyPattern(cur_frpattern, false, result, u_strlen(result),NULL,NULL);
598 
599     for (symType = UNUM_DECIMAL_SEPARATOR_SYMBOL; symType < UNUM_FORMAT_SYMBOL_COUNT; symType++) {
600         status=U_ZERO_ERROR;
601         unum_getSymbol(cur_def, symType, temp1, sizeof(temp1), &status);
602         unum_getSymbol(cur_frpattern, symType, temp2, sizeof(temp2), &status);
603         if(U_FAILURE(status) || u_strcmp(temp1, temp2) != 0)
604         {
605             log_err("Fail: error in getting symbols\n");
606         }
607         else
608             log_verbose("Pass: get and set symbols successful\n");
609     }
610 
611     /*format and check with the previous result */
612 
613     resultlength=0;
614     resultlengthneeded=unum_format(cur_frpattern, l, NULL, resultlength, &pos1, &status);
615     if(status==U_BUFFER_OVERFLOW_ERROR)
616     {
617         status=U_ZERO_ERROR;
618         resultlength=resultlengthneeded+1;
619         unum_format(cur_frpattern, l, temp1, resultlength, &pos1, &status);
620     }
621     if(U_FAILURE(status))
622     {
623         log_err("Error in formatting using unum_format(.....): %s\n", myErrorName(status));
624     }
625     /* TODO:
626      * This test fails because we have not called unum_applyPattern().
627      * Currently, such an applyPattern() does not exist on the C API, and
628      * we have jitterbug 411 for it.
629      * Since it is close to the 1.5 release, I (markus) am disabling this test just
630      * for this release (I added the test itself only last week).
631      * For the next release, we need to fix this.
632      * Then, remove the uprv_strcmp("1.5", ...) and this comment, and the include "cstring.h" at the beginning of this file.
633      */
634     if(u_strcmp(result, temp1) != 0) {
635         log_err("Formatting failed after setting symbols. result=%s temp1=%s\n", result, temp1);
636     }
637 
638 
639     /*----------- */
640 
641 free(result);
642 
643     /* Testing unum_get/setSymbol() */
644     for(i = 0; i < UNUM_FORMAT_SYMBOL_COUNT; ++i) {
645         symbol[0] = (UChar)(0x41 + i);
646         symbol[1] = (UChar)(0x61 + i);
647         unum_setSymbol(cur_frpattern, (UNumberFormatSymbol)i, symbol, 2, &status);
648         if(U_FAILURE(status)) {
649             log_err("Error from unum_setSymbol(%d): %s\n", i, myErrorName(status));
650             return;
651         }
652     }
653     for(i = 0; i < UNUM_FORMAT_SYMBOL_COUNT; ++i) {
654         resultlength = unum_getSymbol(cur_frpattern, (UNumberFormatSymbol)i, symbol, UPRV_LENGTHOF(symbol), &status);
655         if(U_FAILURE(status)) {
656             log_err("Error from unum_getSymbol(%d): %s\n", i, myErrorName(status));
657             return;
658         }
659         if(resultlength != 2 || symbol[0] != 0x41 + i || symbol[1] != 0x61 + i) {
660             log_err("Failure in unum_getSymbol(%d): got unexpected symbol\n", i);
661         }
662     }
663     /*try getting from a bogus symbol*/
664     unum_getSymbol(cur_frpattern, (UNumberFormatSymbol)i, symbol, UPRV_LENGTHOF(symbol), &status);
665     if(U_SUCCESS(status)){
666         log_err("Error : Expected U_ILLEGAL_ARGUMENT_ERROR for bogus symbol");
667     }
668     if(U_FAILURE(status)){
669         if(status != U_ILLEGAL_ARGUMENT_ERROR){
670             log_err("Error: Expected U_ILLEGAL_ARGUMENT_ERROR for bogus symbol, Got %s\n", myErrorName(status));
671         }
672     }
673     status=U_ZERO_ERROR;
674 
675     /* Testing unum_getTextAttribute() and unum_setTextAttribute()*/
676     log_verbose("\nTesting getting and setting text attributes\n");
677     resultlength=5;
678     unum_getTextAttribute(cur_fr, UNUM_NEGATIVE_SUFFIX, temp, resultlength, &status);
679     if(U_FAILURE(status))
680     {
681         log_err("Failure in getting the Text attributes of number format: %s\n", myErrorName(status));
682     }
683     unum_setTextAttribute(cur_def, UNUM_NEGATIVE_SUFFIX, temp, u_strlen(temp), &status);
684     if(U_FAILURE(status))
685     {
686         log_err("Failure in getting the Text attributes of number format: %s\n", myErrorName(status));
687     }
688     unum_getTextAttribute(cur_def, UNUM_NEGATIVE_SUFFIX, suffix, resultlength, &status);
689     if(U_FAILURE(status))
690     {
691         log_err("Failure in getting the Text attributes of number format: %s\n", myErrorName(status));
692     }
693     if(u_strcmp(suffix,temp)!=0)
694         log_err("Fail:Error in setTextAttribute or getTextAttribute in setting and getting suffix\n");
695     else
696         log_verbose("Pass: setting and getting suffix works fine\n");
697     /*set it back to normal */
698     u_uastrcpy(temp,"$");
699     unum_setTextAttribute(cur_def, UNUM_NEGATIVE_SUFFIX, temp, u_strlen(temp), &status);
700 
701     /*checking some more text setter conditions */
702     u_uastrcpy(prefix, "+");
703     unum_setTextAttribute(def, UNUM_POSITIVE_PREFIX, prefix, u_strlen(prefix) , &status);
704     if(U_FAILURE(status))
705     {
706         log_err("error in setting the text attributes : %s\n", myErrorName(status));
707     }
708     unum_getTextAttribute(def, UNUM_POSITIVE_PREFIX, temp, resultlength, &status);
709     if(U_FAILURE(status))
710     {
711         log_err("error in getting the text attributes : %s\n", myErrorName(status));
712     }
713 
714     if(u_strcmp(prefix, temp)!=0)
715         log_err("ERROR: get and setTextAttributes with positive prefix failed\n");
716     else
717         log_verbose("Pass: get and setTextAttributes with positive prefix works fine\n");
718 
719     u_uastrcpy(prefix, "+");
720     unum_setTextAttribute(def, UNUM_NEGATIVE_PREFIX, prefix, u_strlen(prefix), &status);
721     if(U_FAILURE(status))
722     {
723         log_err("error in setting the text attributes : %s\n", myErrorName(status));
724     }
725     unum_getTextAttribute(def, UNUM_NEGATIVE_PREFIX, temp, resultlength, &status);
726     if(U_FAILURE(status))
727     {
728         log_err("error in getting the text attributes : %s\n", myErrorName(status));
729     }
730     if(u_strcmp(prefix, temp)!=0)
731         log_err("ERROR: get and setTextAttributes with negative prefix failed\n");
732     else
733         log_verbose("Pass: get and setTextAttributes with negative prefix works fine\n");
734 
735     u_uastrcpy(suffix, "+");
736     unum_setTextAttribute(def, UNUM_NEGATIVE_SUFFIX, suffix, u_strlen(suffix) , &status);
737     if(U_FAILURE(status))
738     {
739         log_err("error in setting the text attributes: %s\n", myErrorName(status));
740     }
741 
742     unum_getTextAttribute(def, UNUM_NEGATIVE_SUFFIX, temp, resultlength, &status);
743     if(U_FAILURE(status))
744     {
745         log_err("error in getting the text attributes : %s\n", myErrorName(status));
746     }
747     if(u_strcmp(suffix, temp)!=0)
748         log_err("ERROR: get and setTextAttributes with negative suffix failed\n");
749     else
750         log_verbose("Pass: get and settextAttributes with negative suffix works fine\n");
751 
752     u_uastrcpy(suffix, "++");
753     unum_setTextAttribute(def, UNUM_POSITIVE_SUFFIX, suffix, u_strlen(suffix) , &status);
754     if(U_FAILURE(status))
755     {
756         log_err("error in setting the text attributes: %s\n", myErrorName(status));
757     }
758 
759     unum_getTextAttribute(def, UNUM_POSITIVE_SUFFIX, temp, resultlength, &status);
760     if(U_FAILURE(status))
761     {
762         log_err("error in getting the text attributes : %s\n", myErrorName(status));
763     }
764     if(u_strcmp(suffix, temp)!=0)
765         log_err("ERROR: get and setTextAttributes with negative suffix failed\n");
766     else
767         log_verbose("Pass: get and settextAttributes with negative suffix works fine\n");
768 
769     /*Testing unum_getAttribute and  unum_setAttribute() */
770     log_verbose("\nTesting get and set Attributes\n");
771     attr=UNUM_GROUPING_SIZE;
772     assertTrue("unum_hasAttribute returned false for UNUM_GROUPING_SIZE", unum_hasAttribute(def, attr));
773     newvalue=unum_getAttribute(def, attr);
774     newvalue=2;
775     unum_setAttribute(def, attr, newvalue);
776     if(unum_getAttribute(def,attr)!=2)
777         log_err("Fail: error in setting and getting attributes for UNUM_GROUPING_SIZE\n");
778     else
779         log_verbose("Pass: setting and getting attributes for UNUM_GROUPING_SIZE works fine\n");
780 
781     attr=UNUM_MULTIPLIER;
782     assertTrue("unum_hasAttribute returned false for UNUM_MULTIPLIER", unum_hasAttribute(def, attr));
783     newvalue=unum_getAttribute(def, attr);
784     newvalue=8;
785     unum_setAttribute(def, attr, newvalue);
786     if(unum_getAttribute(def,attr) != 8)
787         log_err("error in setting and getting attributes for UNUM_MULTIPLIER\n");
788     else
789         log_verbose("Pass:setting and getting attributes for UNUM_MULTIPLIER works fine\n");
790 
791     attr=UNUM_SECONDARY_GROUPING_SIZE;
792     assertTrue("unum_hasAttribute returned false for UNUM_SECONDARY_GROUPING_SIZE", unum_hasAttribute(def, attr));
793     newvalue=unum_getAttribute(def, attr);
794     newvalue=2;
795     unum_setAttribute(def, attr, newvalue);
796     if(unum_getAttribute(def,attr) != 2)
797         log_err("error in setting and getting attributes for UNUM_SECONDARY_GROUPING_SIZE: got %d\n",
798                 unum_getAttribute(def,attr));
799     else
800         log_verbose("Pass:setting and getting attributes for UNUM_SECONDARY_GROUPING_SIZE works fine\n");
801 
802     /*testing set and get Attributes extensively */
803     log_verbose("\nTesting get and set attributes extensively\n");
804     for(attr=UNUM_PARSE_INT_ONLY; attr<= UNUM_PADDING_POSITION; attr=(UNumberFormatAttribute)((int32_t)attr + 1) )
805     {
806         assertTrue("unum_hasAttribute returned false", unum_hasAttribute(fr, attr));
807         newvalue=unum_getAttribute(fr, attr);
808         unum_setAttribute(def, attr, newvalue);
809         if(unum_getAttribute(def,attr)!=unum_getAttribute(fr, attr))
810             log_err("error in setting and getting attributes\n");
811         else
812             log_verbose("Pass: attributes set and retrieved successfully\n");
813     }
814 
815     /*testing spellout format to make sure we can use it successfully.*/
816     log_verbose("\nTesting spellout format\n");
817     if (spellout_def)
818     {
819         // check that unum_hasAttribute() works right with a spellout formatter
820         assertTrue("unum_hasAttribute() returned true for UNUM_MULTIPLIER on a spellout formatter", !unum_hasAttribute(spellout_def, UNUM_MULTIPLIER));
821         assertTrue("unum_hasAttribute() returned false for UNUM_LENIENT_PARSE on a spellout formatter", unum_hasAttribute(spellout_def, UNUM_LENIENT_PARSE));
822 
823         static const int32_t values[] = { 0, -5, 105, 1005, 105050 };
824         for (i = 0; i < UPRV_LENGTHOF(values); ++i) {
825             UChar buffer[128];
826             int32_t len;
827             int32_t value = values[i];
828             status = U_ZERO_ERROR;
829             len = unum_format(spellout_def, value, buffer, UPRV_LENGTHOF(buffer), NULL, &status);
830             if(U_FAILURE(status)) {
831                 log_err("Error in formatting using unum_format(spellout_fmt, ...): %s\n", myErrorName(status));
832             } else {
833                 int32_t pp = 0;
834                 int32_t parseResult;
835                 /*ustrToAstr(buffer, len, logbuf, UPRV_LENGTHOF(logbuf));*/
836                 log_verbose("formatted %d as '%s', length: %d\n", value, aescstrdup(buffer, len), len);
837 
838                 parseResult = unum_parse(spellout_def, buffer, len, &pp, &status);
839                 if (U_FAILURE(status)) {
840                     log_err("Error in parsing using unum_format(spellout_fmt, ...): %s\n", myErrorName(status));
841                 } else if (parseResult != value) {
842                     log_err("unum_format result %d != value %d\n", parseResult, value);
843                 }
844             }
845         }
846     }
847     else {
848         log_err("Spellout format is unavailable\n");
849     }
850 
851     {    /* Test for ticket #7079 */
852         UNumberFormat* dec_en;
853         UChar groupingSep[] = { 0 };
854         UChar numPercent[] = { 0x0031, 0x0032, 0x0025, 0 }; /* "12%" */
855         double parseResult = 0.0;
856 
857         status=U_ZERO_ERROR;
858         dec_en = unum_open(UNUM_DECIMAL, NULL, 0, "en_US", NULL, &status);
859         unum_setAttribute(dec_en, UNUM_LENIENT_PARSE, 0);
860         unum_setSymbol(dec_en, UNUM_GROUPING_SEPARATOR_SYMBOL, groupingSep, 0, &status);
861         parseResult = unum_parseDouble(dec_en, numPercent, -1, NULL, &status);
862         /* Without the fix in #7079, the above call will hang */
863         if ( U_FAILURE(status) || parseResult != 12.0 ) {
864             log_err("unum_parseDouble with empty groupingSep: status %s, parseResult %f not 12.0\n",
865                     myErrorName(status), parseResult);
866         } else {
867             log_verbose("unum_parseDouble with empty groupingSep: no hang, OK\n");
868         }
869         unum_close(dec_en);
870     }
871 
872     {   /* Test parse & format of big decimals.  Use a number with too many digits to fit in a double,
873                                          to verify that it is taking the pure decimal path. */
874         UNumberFormat *fmt;
875         const char *bdpattern = "#,##0.#########";
876         const char *numInitial     = "12345678900987654321.1234567896";
877         const char *numFormatted  = "12,345,678,900,987,654,321.12345679";
878         const char *parseExpected = "1.234567890098765432112345679E+19";
879         const char *parseExpected2 = "3.4567890098765432112345679E+17";
880         int32_t resultSize    = 0;
881         int32_t parsePos      = 0;     /* Output parameter for Parse operations. */
882         #define DESTCAPACITY 100
883         UChar dest[DESTCAPACITY];
884         char  desta[DESTCAPACITY];
885         UFieldPosition fieldPos = {0};
886 
887         /* Format */
888 
889         status = U_ZERO_ERROR;
890         u_uastrcpy(dest, bdpattern);
891         fmt = unum_open(UNUM_PATTERN_DECIMAL, dest, -1, "en", NULL /*parseError*/, &status);
892         if (U_FAILURE(status)) log_err("File %s, Line %d, status = %s\n", __FILE__, __LINE__, u_errorName(status));
893 
894         resultSize = unum_formatDecimal(fmt, numInitial, -1, dest, DESTCAPACITY, NULL, &status);
895         if (U_FAILURE(status)) {
896             log_err("File %s, Line %d, status = %s\n", __FILE__, __LINE__, u_errorName(status));
897         }
898         u_austrncpy(desta, dest, DESTCAPACITY);
899         if (strcmp(numFormatted, desta) != 0) {
900             log_err("File %s, Line %d, (expected, actual) =  (\"%s\", \"%s\")\n",
901                     __FILE__, __LINE__, numFormatted, desta);
902         }
903         if ((int32_t)strlen(numFormatted) != resultSize) {
904             log_err("File %s, Line %d, (expected, actual) = (%d, %d)\n",
905                      __FILE__, __LINE__, (int32_t)strlen(numFormatted), resultSize);
906         }
907 
908         /* Format with a FieldPosition parameter */
909 
910         fieldPos.field = UNUM_DECIMAL_SEPARATOR_FIELD;
911         resultSize = unum_formatDecimal(fmt, numInitial, -1, dest, DESTCAPACITY, &fieldPos, &status);
912         if (U_FAILURE(status)) {
913             log_err("File %s, Line %d, status = %s\n", __FILE__, __LINE__, u_errorName(status));
914         }
915         u_austrncpy(desta, dest, DESTCAPACITY);
916         if (strcmp(numFormatted, desta) != 0) {
917             log_err("File %s, Line %d, (expected, actual) =  (\"%s\", \"%s\")\n",
918                     __FILE__, __LINE__, numFormatted, desta);
919         }
920         if (fieldPos.beginIndex != 26) {  /* index of "." in formatted number */
921             log_err("File %s, Line %d, (expected, actual) =  (%d, %d)\n",
922                     __FILE__, __LINE__, 0, fieldPos.beginIndex);
923         }
924         if (fieldPos.endIndex != 27) {
925             log_err("File %s, Line %d, (expected, actual) =  (%d, %d)\n",
926                     __FILE__, __LINE__, 0, fieldPos.endIndex);
927         }
928 
929         /* Parse */
930 
931         status = U_ZERO_ERROR;
932         u_uastrcpy(dest, numFormatted);   /* Parse the expected output of the formatting test */
933         resultSize = unum_parseDecimal(fmt, dest, -1, NULL, desta, DESTCAPACITY, &status);
934         if (U_FAILURE(status)) {
935             log_err("File %s, Line %d, status = %s\n", __FILE__, __LINE__, u_errorName(status));
936         }
937         if (uprv_strcmp(parseExpected, desta) != 0) {
938             log_err("File %s, Line %d, (expected, actual) = (\"%s\", \"%s\")\n",
939                     __FILE__, __LINE__, parseExpected, desta);
940         } else {
941             log_verbose("File %s, Line %d, got expected = \"%s\"\n",
942                     __FILE__, __LINE__, desta);
943         }
944         if ((int32_t)strlen(parseExpected) != resultSize) {
945             log_err("File %s, Line %d, (expected, actual) = (%d, %d)\n",
946                     __FILE__, __LINE__, (int32_t)strlen(parseExpected), resultSize);
947         }
948 
949         /* Parse with a parsePos parameter */
950 
951         status = U_ZERO_ERROR;
952         u_uastrcpy(dest, numFormatted);   /* Parse the expected output of the formatting test */
953         parsePos = 3;                 /*      12,345,678,900,987,654,321.12345679         */
954                                       /* start parsing at the the third char              */
955         resultSize = unum_parseDecimal(fmt, dest, -1, &parsePos, desta, DESTCAPACITY, &status);
956         if (U_FAILURE(status)) {
957             log_err("File %s, Line %d, status = %s\n", __FILE__, __LINE__, u_errorName(status));
958         }
959         if (strcmp(parseExpected2, desta) != 0) {   /*  "3.4567890098765432112345679E+17" */
960             log_err("File %s, Line %d, (expected, actual) = (\"%s\", \"%s\")\n",
961                     __FILE__, __LINE__, parseExpected2, desta);
962         } else {
963             log_verbose("File %s, Line %d, got expected = \"%s\"\n",
964                     __FILE__, __LINE__, desta);
965         }
966         if ((int32_t)strlen(numFormatted) != parsePos) {
967             log_err("File %s, Line %d, parsePos (expected, actual) = (\"%d\", \"%d\")\n",
968                     __FILE__, __LINE__, (int32_t)strlen(parseExpected), parsePos);
969         }
970 
971         unum_close(fmt);
972     }
973 
974     status = U_ZERO_ERROR;
975     /* Test invalid symbol argument */
976     {
977         int32_t badsymbolLarge = UNUM_FORMAT_SYMBOL_COUNT + 1;
978         int32_t badsymbolSmall = -1;
979         UChar value[10];
980         int32_t valueLength = 10;
981         UNumberFormat *fmt = unum_open(UNUM_DEFAULT, NULL, 0, NULL, NULL, &status);
982         if (U_FAILURE(status)) {
983             log_err("File %s, Line %d, status = %s\n", __FILE__, __LINE__, u_errorName(status));
984         } else {
985             unum_getSymbol(fmt, (UNumberFormatSymbol)badsymbolLarge, NULL, 0, &status);
986             if (U_SUCCESS(status)) log_err("unum_getSymbol()'s status should be ILLEGAL_ARGUMENT with invalid symbol (> UNUM_FORMAT_SYMBOL_COUNT) argument\n");
987 
988             status = U_ZERO_ERROR;
989             unum_getSymbol(fmt, (UNumberFormatSymbol)badsymbolSmall, NULL, 0, &status);
990             if (U_SUCCESS(status)) log_err("unum_getSymbol()'s status should be ILLEGAL_ARGUMENT with invalid symbol (less than 0) argument\n");
991 
992             status = U_ZERO_ERROR;
993             unum_setSymbol(fmt, (UNumberFormatSymbol)badsymbolLarge, value, valueLength, &status);
994             if (U_SUCCESS(status)) log_err("unum_setSymbol()'s status should be ILLEGAL_ARGUMENT with invalid symbol (> UNUM_FORMAT_SYMBOL_COUNT) argument\n");
995 
996             status = U_ZERO_ERROR;
997             unum_setSymbol(fmt, (UNumberFormatSymbol)badsymbolSmall, value, valueLength, &status);
998             if (U_SUCCESS(status)) log_err("unum_setSymbol()'s status should be ILLEGAL_ARGUMENT with invalid symbol (less than 0) argument\n");
999 
1000             unum_close(fmt);
1001         }
1002     }
1003 
1004 
1005     /*closing the NumberFormat() using unum_close(UNumberFormat*)")*/
1006     unum_close(def);
1007     unum_close(fr);
1008     unum_close(cur_def);
1009     unum_close(cur_fr);
1010     unum_close(per_def);
1011     unum_close(per_fr);
1012     unum_close(spellout_def);
1013     unum_close(pattern);
1014     unum_close(cur_frpattern);
1015     unum_close(myclone);
1016 
1017 }
1018 
TestParseZero(void)1019 static void TestParseZero(void)
1020 {
1021     UErrorCode errorCode = U_ZERO_ERROR;
1022     UChar input[] = {0x30, 0};   /*  Input text is decimal '0' */
1023     UChar pat[] = {0x0023,0x003b,0x0023,0}; /*  {'#', ';', '#', 0}; */
1024     double  dbl;
1025 
1026 #if 0
1027     UNumberFormat* unum = unum_open( UNUM_DECIMAL /*or UNUM_DEFAULT*/, NULL, -1, NULL, NULL, &errorCode);
1028 #else
1029     UNumberFormat* unum = unum_open( UNUM_PATTERN_DECIMAL /*needs pattern*/, pat, -1, NULL, NULL, &errorCode);
1030 #endif
1031 
1032     dbl = unum_parseDouble( unum, input, -1 /*u_strlen(input)*/, 0 /* 0 = start */, &errorCode );
1033     if (U_FAILURE(errorCode)) {
1034         log_data_err("Result - %s\n", u_errorName(errorCode));
1035     } else {
1036         log_verbose("Double: %f\n", dbl);
1037     }
1038     unum_close(unum);
1039 }
1040 
1041 static const UChar dollars2Sym[] = { 0x24,0x32,0x2E,0x30,0x30,0 }; /* $2.00 */
1042 static const UChar dollars4Sym[] = { 0x24,0x34,0 }; /* $4 */
1043 static const UChar dollarsUS4Sym[] = { 0x55,0x53,0x24,0x34,0 }; /* US$4 */
1044 static const UChar dollars9Sym[] = { 0x39,0xA0,0x24,0 }; /* 9 $ */
1045 static const UChar pounds3Sym[]  = { 0xA3,0x33,0x2E,0x30,0x30,0 }; /* [POUND]3.00 */
1046 static const UChar pounds5Sym[]  = { 0xA3,0x35,0 }; /* [POUND]5 */
1047 static const UChar pounds7Sym[]  = { 0x37,0xA0,0xA3,0 }; /* 7 [POUND] */
1048 static const UChar euros4Sym[]   = { 0x34,0x2C,0x30,0x30,0xA0,0x20AC,0 }; /* 4,00 [EURO] */
1049 static const UChar euros6Sym[]   = { 0x36,0xA0,0x20AC,0 }; /* 6 [EURO] */
1050 static const UChar euros8Sym[]   = { 0x20AC,0x38,0 }; /* [EURO]8 */
1051 static const UChar dollars4PluEn[] = { 0x34,0x20,0x55,0x53,0x20,0x64,0x6F,0x6C,0x6C,0x61,0x72,0x73,0 }; /* 4 US dollars*/
1052 static const UChar pounds5PluEn[]  = { 0x35,0x20,0x42,0x72,0x69,0x74,0x69,0x73,0x68,0x20,0x70,0x6F,0x75,0x6E,0x64,0x73,0x20,0x73,0x74,0x65,0x72,0x6C,0x69,0x6E,0x67,0 }; /* 5 British pounds sterling */
1053 static const UChar euros8PluEn[]   = { 0x38,0x20,0x65,0x75,0x72,0x6F,0x73,0 }; /* 8 euros*/
1054 static const UChar euros6PluFr[]   = { 0x36,0x20,0x65,0x75,0x72,0x6F,0x73,0 }; /* 6 euros*/
1055 
1056 typedef struct {
1057     const char *  locale;
1058     const char *  descrip;
1059     const UChar * currStr;
1060     const UChar * plurStr;
1061     UErrorCode    parsDoubExpectErr;
1062     int32_t       parsDoubExpectPos;
1063     double        parsDoubExpectVal;
1064     UErrorCode    parsCurrExpectErr;
1065     int32_t       parsCurrExpectPos;
1066     double        parsCurrExpectVal;
1067     const char *  parsCurrExpectCurr;
1068 } ParseCurrencyItem;
1069 
1070 static const ParseCurrencyItem parseCurrencyItems[] = {
1071     { "en_US", "dollars2", dollars2Sym, NULL,           U_ZERO_ERROR,  5, 2.0, U_ZERO_ERROR,  5, 2.0, "USD" },
1072     { "en_US", "dollars4", dollars4Sym, dollars4PluEn,  U_ZERO_ERROR,  2, 4.0, U_ZERO_ERROR,  2, 4.0, "USD" },
1073     { "en_US", "dollars9", dollars9Sym, NULL,           U_PARSE_ERROR, 1, 0.0, U_PARSE_ERROR, 1, 0.0, ""    },
1074     { "en_US", "pounds3",  pounds3Sym,  NULL,           U_PARSE_ERROR, 0, 0.0, U_ZERO_ERROR,  5, 3.0, "GBP" },
1075     { "en_US", "pounds5",  pounds5Sym,  pounds5PluEn,   U_PARSE_ERROR, 0, 0.0, U_ZERO_ERROR,  2, 5.0, "GBP" },
1076     { "en_US", "pounds7",  pounds7Sym,  NULL,           U_PARSE_ERROR, 1, 0.0, U_PARSE_ERROR, 1, 0.0, ""    },
1077     { "en_US", "euros8",   euros8Sym,   euros8PluEn,    U_PARSE_ERROR, 0, 0.0, U_ZERO_ERROR,  2, 8.0, "EUR" },
1078 
1079     { "en_GB", "pounds3",  pounds3Sym,  NULL,           U_ZERO_ERROR,  5, 3.0, U_ZERO_ERROR,  5, 3.0, "GBP" },
1080     { "en_GB", "pounds5",  pounds5Sym,  pounds5PluEn,   U_ZERO_ERROR,  2, 5.0, U_ZERO_ERROR,  2, 5.0, "GBP" },
1081     { "en_GB", "pounds7",  pounds7Sym,  NULL,           U_PARSE_ERROR, 1, 0.0, U_PARSE_ERROR, 1, 0.0, ""    },
1082     { "en_GB", "euros4",   euros4Sym,   NULL,           U_PARSE_ERROR, 0, 0.0, U_PARSE_ERROR, 0, 0.0, ""    },
1083     { "en_GB", "euros6",   euros6Sym,   NULL,           U_PARSE_ERROR, 1, 0.0, U_PARSE_ERROR, 1, 0.0, ""    },
1084     { "en_GB", "euros8",   euros8Sym,    euros8PluEn,   U_PARSE_ERROR, 0, 0.0, U_ZERO_ERROR,  2, 8.0, "EUR" },
1085     { "en_GB", "dollars4", dollarsUS4Sym,dollars4PluEn, U_PARSE_ERROR, 0, 0.0, U_ZERO_ERROR,  4, 4.0, "USD" },
1086 
1087     { "fr_FR", "euros4",   euros4Sym,   NULL,           U_ZERO_ERROR,  6, 4.0, U_ZERO_ERROR,  6, 4.0, "EUR" },
1088     { "fr_FR", "euros6",   euros6Sym,   euros6PluFr,    U_ZERO_ERROR,  3, 6.0, U_ZERO_ERROR,  3, 6.0, "EUR" },
1089     { "fr_FR", "euros8",   euros8Sym,   NULL,           U_PARSE_ERROR, 2, 0.0, U_PARSE_ERROR, 2, 0.0, ""    },
1090     { "fr_FR", "dollars2", dollars2Sym, NULL,           U_PARSE_ERROR, 0, 0.0, U_PARSE_ERROR, 0, 0.0, ""    },
1091     { "fr_FR", "dollars4", dollars4Sym, NULL,           U_PARSE_ERROR, 0, 0.0, U_PARSE_ERROR, 0, 0.0, ""    },
1092 
1093     { NULL,    NULL,       NULL,        NULL,           0,             0, 0.0, 0,             0, 0.0, NULL  }
1094 };
1095 
TestParseCurrency()1096 static void TestParseCurrency()
1097 {
1098     const ParseCurrencyItem * itemPtr;
1099     for (itemPtr = parseCurrencyItems; itemPtr->locale != NULL; ++itemPtr) {
1100         UNumberFormat* unum;
1101         UErrorCode status;
1102         double parseVal;
1103         int32_t parsePos;
1104         UChar parseCurr[4];
1105         char parseCurrB[4];
1106 
1107         status = U_ZERO_ERROR;
1108         unum = unum_open(UNUM_CURRENCY, NULL, 0, itemPtr->locale, NULL, &status);
1109         if (U_SUCCESS(status)) {
1110             const UChar * currStr = itemPtr->currStr;
1111             status = U_ZERO_ERROR;
1112             parsePos = 0;
1113             parseVal = unum_parseDouble(unum, currStr, -1, &parsePos, &status);
1114             if (status != itemPtr->parsDoubExpectErr || parsePos != itemPtr->parsDoubExpectPos || parseVal != itemPtr->parsDoubExpectVal) {
1115                 log_err("UNUM_CURRENCY parseDouble %s/%s, expect %s pos %d val %.1f, get %s pos %d val %.1f\n",
1116                         itemPtr->locale, itemPtr->descrip,
1117                         u_errorName(itemPtr->parsDoubExpectErr), itemPtr->parsDoubExpectPos, itemPtr->parsDoubExpectVal,
1118                         u_errorName(status), parsePos, parseVal );
1119             }
1120             status = U_ZERO_ERROR;
1121             parsePos = 0;
1122             parseCurr[0] = 0;
1123             parseVal = unum_parseDoubleCurrency(unum, currStr, -1, &parsePos, parseCurr, &status);
1124             u_austrncpy(parseCurrB, parseCurr, 4);
1125             if (status != itemPtr->parsCurrExpectErr || parsePos != itemPtr->parsCurrExpectPos || parseVal != itemPtr->parsCurrExpectVal ||
1126                     strncmp(parseCurrB, itemPtr->parsCurrExpectCurr, 4) != 0) {
1127                 log_err("UNUM_CURRENCY parseDoubleCurrency %s/%s, expect %s pos %d val %.1f cur %s, get %s pos %d val %.1f cur %s\n",
1128                         itemPtr->locale, itemPtr->descrip,
1129                         u_errorName(itemPtr->parsCurrExpectErr), itemPtr->parsCurrExpectPos, itemPtr->parsCurrExpectVal, itemPtr->parsCurrExpectCurr,
1130                         u_errorName(status), parsePos, parseVal, parseCurrB );
1131             }
1132             unum_close(unum);
1133         } else {
1134             log_data_err("unexpected error in unum_open UNUM_CURRENCY for locale %s: '%s'\n", itemPtr->locale, u_errorName(status));
1135         }
1136 
1137         if (itemPtr->plurStr != NULL) {
1138             status = U_ZERO_ERROR;
1139             unum = unum_open(UNUM_CURRENCY_PLURAL, NULL, 0, itemPtr->locale, NULL, &status);
1140             if (U_SUCCESS(status)) {
1141                 status = U_ZERO_ERROR;
1142                 parsePos = 0;
1143                 parseVal = unum_parseDouble(unum, itemPtr->plurStr, -1, &parsePos, &status);
1144                 if (status != itemPtr->parsDoubExpectErr || parseVal != itemPtr->parsDoubExpectVal) {
1145                     log_err("UNUM_CURRENCY parseDouble Plural %s/%s, expect %s val %.1f, get %s val %.1f\n",
1146                             itemPtr->locale, itemPtr->descrip,
1147                             u_errorName(itemPtr->parsDoubExpectErr), itemPtr->parsDoubExpectVal,
1148                             u_errorName(status), parseVal );
1149                 }
1150                 status = U_ZERO_ERROR;
1151                 parsePos = 0;
1152                 parseCurr[0] = 0;
1153                 parseVal = unum_parseDoubleCurrency(unum, itemPtr->plurStr, -1, &parsePos, parseCurr, &status);
1154                 u_austrncpy(parseCurrB, parseCurr, 4);
1155                 if (status != itemPtr->parsCurrExpectErr || parseVal != itemPtr->parsCurrExpectVal ||
1156                         strncmp(parseCurrB, itemPtr->parsCurrExpectCurr, 4) != 0) {
1157                     log_err("UNUM_CURRENCY parseDoubleCurrency Plural %s/%s, expect %s val %.1f cur %s, get %s val %.1f cur %s\n",
1158                             itemPtr->locale, itemPtr->descrip,
1159                             u_errorName(itemPtr->parsCurrExpectErr), itemPtr->parsCurrExpectVal, itemPtr->parsCurrExpectCurr,
1160                             u_errorName(status), parseVal, parseCurrB );
1161                 }
1162                 unum_close(unum);
1163             } else {
1164                 log_data_err("unexpected error in unum_open UNUM_CURRENCY_PLURAL for locale %s: '%s'\n", itemPtr->locale, u_errorName(status));
1165             }
1166         }
1167     }
1168 }
1169 
1170 typedef struct {
1171     const char *  testname;
1172     const char *  locale;
1173     const UChar * source;
1174     int32_t       startPos;
1175     int32_t       value;
1176     int32_t       endPos;
1177     UErrorCode    status;
1178 } SpelloutParseTest;
1179 
1180 static const UChar ustr_en0[]   = {0x7A, 0x65, 0x72, 0x6F, 0}; /* zero */
1181 static const UChar ustr_123[]   = {0x31, 0x32, 0x33, 0};       /* 123 */
1182 static const UChar ustr_en123[] = {0x6f, 0x6e, 0x65, 0x20, 0x68, 0x75, 0x6e, 0x64, 0x72, 0x65, 0x64,
1183                                    0x20, 0x74, 0x77, 0x65, 0x6e, 0x74, 0x79,
1184                                    0x2d, 0x74, 0x68, 0x72, 0x65, 0x65, 0}; /* one hundred twenty-three */
1185 static const UChar ustr_fr123[] = {0x63, 0x65, 0x6e, 0x74, 0x20, 0x76, 0x69, 0x6e, 0x67, 0x74, 0x2d,
1186                                    0x74, 0x72, 0x6f, 0x69, 0x73, 0};       /* cent vingt-trois */
1187 static const UChar ustr_ja123[] = {0x767e, 0x4e8c, 0x5341, 0x4e09, 0};     /* kanji 100(+)2(*)10(+)3 */
1188 
1189 static const SpelloutParseTest spelloutParseTests[] = {
1190     /* name    loc   src       start val  end status */
1191     { "en0",   "en", ustr_en0,    0,   0,  4, U_ZERO_ERROR },
1192     { "en0",   "en", ustr_en0,    2,   0,  2, U_PARSE_ERROR },
1193     { "en0",   "ja", ustr_en0,    0,   0,  0, U_PARSE_ERROR },
1194     { "123",   "en", ustr_123,    0, 123,  3, U_ZERO_ERROR },
1195     { "en123", "en", ustr_en123,  0, 123, 24, U_ZERO_ERROR },
1196     { "en123", "en", ustr_en123, 12,  23, 24, U_ZERO_ERROR },
1197     { "en123", "fr", ustr_en123, 16,   0, 16, U_PARSE_ERROR },
1198     { "fr123", "fr", ustr_fr123,  0, 123, 16, U_ZERO_ERROR },
1199     { "fr123", "fr", ustr_fr123,  5,  23, 16, U_ZERO_ERROR },
1200     { "fr123", "en", ustr_fr123,  0,   0,  0, U_PARSE_ERROR },
1201     { "ja123", "ja", ustr_ja123,  0, 123,  4, U_ZERO_ERROR },
1202     { "ja123", "ja", ustr_ja123,  1,  23,  4, U_ZERO_ERROR },
1203     { "ja123", "fr", ustr_ja123,  0,   0,  0, U_PARSE_ERROR },
1204     { NULL,    NULL, NULL,        0,   0,  0, 0 } /* terminator */
1205 };
1206 
TestSpelloutNumberParse()1207 static void TestSpelloutNumberParse()
1208 {
1209     const SpelloutParseTest * testPtr;
1210     for (testPtr = spelloutParseTests; testPtr->testname != NULL; ++testPtr) {
1211         UErrorCode status = U_ZERO_ERROR;
1212         int32_t value, position = testPtr->startPos;
1213         UNumberFormat *nf = unum_open(UNUM_SPELLOUT, NULL, 0, testPtr->locale, NULL, &status);
1214         if (U_FAILURE(status)) {
1215             log_err_status(status, "unum_open fails for UNUM_SPELLOUT with locale %s, status %s\n", testPtr->locale, myErrorName(status));
1216             continue;
1217         }
1218         status = U_ZERO_ERROR;
1219         value = unum_parse(nf, testPtr->source, -1, &position, &status);
1220         if ( value != testPtr->value || position != testPtr->endPos || status != testPtr->status ) {
1221             log_err("unum_parse SPELLOUT, locale %s, testname %s, startPos %d: for value / endPos / status, expected %d / %d / %s, got %d / %d / %s\n",
1222                     testPtr->locale, testPtr->testname, testPtr->startPos,
1223                     testPtr->value, testPtr->endPos, myErrorName(testPtr->status),
1224                     value, position, myErrorName(status) );
1225         }
1226         unum_close(nf);
1227     }
1228 }
1229 
TestSignificantDigits()1230 static void TestSignificantDigits()
1231 {
1232     UChar temp[128];
1233     int32_t resultlengthneeded;
1234     int32_t resultlength;
1235     UErrorCode status = U_ZERO_ERROR;
1236     UChar *result = NULL;
1237     UNumberFormat* fmt;
1238     double d = 123456.789;
1239 
1240     u_uastrcpy(temp, "###0.0#");
1241     fmt=unum_open(UNUM_IGNORE, temp, -1, "en", NULL, &status);
1242     if (U_FAILURE(status)) {
1243         log_data_err("got unexpected error for unum_open: '%s'\n", u_errorName(status));
1244         return;
1245     }
1246     unum_setAttribute(fmt, UNUM_SIGNIFICANT_DIGITS_USED, true);
1247     unum_setAttribute(fmt, UNUM_MAX_SIGNIFICANT_DIGITS, 6);
1248 
1249     u_uastrcpy(temp, "123457");
1250     resultlength=0;
1251     resultlengthneeded=unum_formatDouble(fmt, d, NULL, resultlength, NULL, &status);
1252     if(status==U_BUFFER_OVERFLOW_ERROR)
1253     {
1254         status=U_ZERO_ERROR;
1255         resultlength=resultlengthneeded+1;
1256         result=(UChar*)malloc(sizeof(UChar) * resultlength);
1257         unum_formatDouble(fmt, d, result, resultlength, NULL, &status);
1258     }
1259     if(U_FAILURE(status))
1260     {
1261         log_err("Error in formatting using unum_formatDouble(.....): %s\n", myErrorName(status));
1262         return;
1263     }
1264     if(u_strcmp(result, temp)==0)
1265         log_verbose("Pass: Number Formatting using unum_formatDouble() Successful\n");
1266     else
1267         log_err("FAIL: Error in number formatting using unum_formatDouble()\n");
1268     free(result);
1269     unum_close(fmt);
1270 }
1271 
TestSigDigRounding()1272 static void TestSigDigRounding()
1273 {
1274     UErrorCode status = U_ZERO_ERROR;
1275     UChar expected[128];
1276     UChar result[128];
1277     char  temp1[128];
1278     char  temp2[128];
1279     UNumberFormat* fmt;
1280     double d = 123.4;
1281 
1282     fmt=unum_open(UNUM_DECIMAL, NULL, 0, "en", NULL, &status);
1283     if (U_FAILURE(status)) {
1284         log_data_err("got unexpected error for unum_open: '%s'\n", u_errorName(status));
1285         return;
1286     }
1287     unum_setAttribute(fmt, UNUM_LENIENT_PARSE, false);
1288     unum_setAttribute(fmt, UNUM_SIGNIFICANT_DIGITS_USED, true);
1289     unum_setAttribute(fmt, UNUM_MAX_SIGNIFICANT_DIGITS, 2);
1290     /* unum_setAttribute(fmt, UNUM_MAX_FRACTION_DIGITS, 0); */
1291 
1292     unum_setAttribute(fmt, UNUM_ROUNDING_MODE, UNUM_ROUND_UP);
1293     unum_setDoubleAttribute(fmt, UNUM_ROUNDING_INCREMENT, 20.0);
1294 
1295     (void)unum_formatDouble(fmt, d, result, UPRV_LENGTHOF(result), NULL, &status);
1296     if(U_FAILURE(status))
1297     {
1298         log_err("Error in formatting using unum_formatDouble(.....): %s\n", myErrorName(status));
1299         return;
1300     }
1301 
1302     u_uastrcpy(expected, "140");
1303     if(u_strcmp(result, expected)!=0)
1304         log_err("FAIL: Error in unum_formatDouble result %s instead of %s\n", u_austrcpy(temp1, result), u_austrcpy(temp2, expected) );
1305 
1306     unum_close(fmt);
1307 }
1308 
TestNumberFormatPadding()1309 static void TestNumberFormatPadding()
1310 {
1311     UChar *result=NULL;
1312     UChar temp1[512];
1313     UChar temp2[512];
1314 
1315     UErrorCode status=U_ZERO_ERROR;
1316     int32_t resultlength;
1317     int32_t resultlengthneeded;
1318     UNumberFormat *pattern;
1319     double d1;
1320     double d = -10456.37;
1321     UFieldPosition pos1;
1322     int32_t parsepos;
1323 
1324     /* create a number format using unum_openPattern(....)*/
1325     log_verbose("\nTesting unum_openPattern() with padding\n");
1326     u_uastrcpy(temp1, "*#,##0.0#*;(#,##0.0#)");
1327     status=U_ZERO_ERROR;
1328     pattern=unum_open(UNUM_IGNORE,temp1, u_strlen(temp1), NULL, NULL,&status);
1329     if(U_SUCCESS(status))
1330     {
1331         log_err("error in unum_openPattern(%s): %s\n", temp1, myErrorName(status) );
1332     }
1333     else
1334     {
1335         unum_close(pattern);
1336     }
1337 
1338 /*    u_uastrcpy(temp1, "*x#,###,###,##0.0#;(*x#,###,###,##0.0#)"); */
1339     u_uastrcpy(temp1, "*x#,###,###,##0.0#;*x(###,###,##0.0#)"); // input pattern
1340     u_uastrcpy(temp2, "*x#########,##0.0#;(#########,##0.0#)"); // equivalent (?) output pattern
1341     status=U_ZERO_ERROR;
1342     pattern=unum_open(UNUM_IGNORE,temp1, u_strlen(temp1), "en_US",NULL, &status);
1343     if(U_FAILURE(status))
1344     {
1345         log_err_status(status, "error in padding unum_openPattern(%s): %s\n", temp1, myErrorName(status) );
1346     }
1347     else {
1348         log_verbose("Pass: padding unum_openPattern() works fine\n");
1349 
1350         /*test for unum_toPattern()*/
1351         log_verbose("\nTesting padding unum_toPattern()\n");
1352         resultlength=0;
1353         resultlengthneeded=unum_toPattern(pattern, false, NULL, resultlength, &status);
1354         if(status==U_BUFFER_OVERFLOW_ERROR)
1355         {
1356             status=U_ZERO_ERROR;
1357             resultlength=resultlengthneeded+1;
1358             result=(UChar*)malloc(sizeof(UChar) * resultlength);
1359             unum_toPattern(pattern, false, result, resultlength, &status);
1360         }
1361         if(U_FAILURE(status))
1362         {
1363             log_err("error in extracting the padding pattern from UNumberFormat: %s\n", myErrorName(status));
1364         }
1365         else
1366         {
1367             if(u_strncmp(result, temp2, resultlengthneeded)!=0) {
1368                 log_err(
1369                         "FAIL: Error in extracting the padding pattern using unum_toPattern(): %d: %s != %s\n",
1370                         resultlengthneeded,
1371                         austrdup(temp2),
1372                         austrdup(result));
1373             } else {
1374                 log_verbose("Pass: extracted the padding pattern correctly using unum_toPattern()\n");
1375             }
1376         }
1377         free(result);
1378 /*        u_uastrcpy(temp1, "(xxxxxxx10,456.37)"); */
1379         u_uastrcpy(temp1, "xxxxx(10,456.37)");
1380         resultlength=0;
1381         pos1.field = UNUM_FRACTION_FIELD;
1382         resultlengthneeded=unum_formatDouble(pattern, d, NULL, resultlength, &pos1, &status);
1383         if(status==U_BUFFER_OVERFLOW_ERROR)
1384         {
1385             status=U_ZERO_ERROR;
1386             resultlength=resultlengthneeded+1;
1387             result=(UChar*)malloc(sizeof(UChar) * resultlength);
1388             unum_formatDouble(pattern, d, result, resultlength, NULL, &status);
1389         }
1390         if(U_FAILURE(status))
1391         {
1392             log_err("Error in formatting using unum_formatDouble(.....) with padding : %s\n", myErrorName(status));
1393         }
1394         else
1395         {
1396             if(u_strcmp(result, temp1)==0)
1397                 log_verbose("Pass: Number Formatting using unum_formatDouble() padding Successful\n");
1398             else
1399                 log_data_err("FAIL: Error in number formatting using unum_formatDouble() with padding\n");
1400             if(pos1.beginIndex == 13 && pos1.endIndex == 15)
1401                 log_verbose("Pass: Complete number formatting using unum_formatDouble() successful\n");
1402             else
1403                 log_err("Fail: Error in complete number Formatting using unum_formatDouble()\nGot: b=%d end=%d\nExpected: b=13 end=15\n",
1404                         pos1.beginIndex, pos1.endIndex);
1405 
1406 
1407             /* Testing unum_parse() and unum_parseDouble() */
1408             log_verbose("\nTesting padding unum_parseDouble()\n");
1409             parsepos=0;
1410             d1=unum_parseDouble(pattern, result, u_strlen(result), &parsepos, &status);
1411             if(U_FAILURE(status))
1412             {
1413                 log_err("padding parse failed. The error is : %s\n", myErrorName(status));
1414             }
1415 
1416             if(d1!=d)
1417                 log_err("Fail: Error in padding parsing\n");
1418             else
1419                 log_verbose("Pass: padding parsing successful\n");
1420 free(result);
1421         }
1422     }
1423 
1424     unum_close(pattern);
1425 }
1426 
1427 static UBool
withinErr(double a,double b,double err)1428 withinErr(double a, double b, double err) {
1429     return uprv_fabs(a - b) < uprv_fabs(a * err);
1430 }
1431 
TestInt64Format()1432 static void TestInt64Format() {
1433     UChar temp1[512];
1434     UChar result[512];
1435     UNumberFormat *fmt;
1436     UErrorCode status = U_ZERO_ERROR;
1437     const double doubleInt64Max = (double)U_INT64_MAX;
1438     const double doubleInt64Min = (double)U_INT64_MIN;
1439     const double doubleBig = 10.0 * (double)U_INT64_MAX;
1440     int32_t val32;
1441     int64_t val64;
1442     double  valDouble;
1443     int32_t parsepos;
1444 
1445     /* create a number format using unum_openPattern(....) */
1446     log_verbose("\nTesting Int64Format\n");
1447     u_uastrcpy(temp1, "#.#E0");
1448     fmt = unum_open(UNUM_IGNORE, temp1, u_strlen(temp1), "en_US", NULL, &status);
1449     if(U_FAILURE(status)) {
1450         log_data_err("error in unum_openPattern() - %s\n", myErrorName(status));
1451     } else {
1452         unum_setAttribute(fmt, UNUM_MAX_FRACTION_DIGITS, 20);
1453         unum_formatInt64(fmt, U_INT64_MAX, result, 512, NULL, &status);
1454         if (U_FAILURE(status)) {
1455             log_err("error in unum_format(): %s\n", myErrorName(status));
1456         } else {
1457             log_verbose("format int64max: '%s'\n", result);
1458             parsepos = 0;
1459             val32 = unum_parse(fmt, result, u_strlen(result), &parsepos, &status);
1460             if (status != U_INVALID_FORMAT_ERROR) {
1461                 log_err("parse didn't report error: %s\n", myErrorName(status));
1462             } else if (val32 != INT32_MAX) {
1463                 log_err("parse didn't pin return value, got: %d\n", val32);
1464             }
1465 
1466             status = U_ZERO_ERROR;
1467             parsepos = 0;
1468             val64 = unum_parseInt64(fmt, result, u_strlen(result), &parsepos, &status);
1469             if (U_FAILURE(status)) {
1470                 log_err("parseInt64 returned error: %s\n", myErrorName(status));
1471             } else if (val64 != U_INT64_MAX) {
1472                 log_err("parseInt64 returned incorrect value, got: %ld\n", val64);
1473             }
1474 
1475             status = U_ZERO_ERROR;
1476             parsepos = 0;
1477             valDouble = unum_parseDouble(fmt, result, u_strlen(result), &parsepos, &status);
1478             if (U_FAILURE(status)) {
1479                 log_err("parseDouble returned error: %s\n", myErrorName(status));
1480             } else if (valDouble != doubleInt64Max) {
1481                 log_err("parseDouble returned incorrect value, got: %g\n", valDouble);
1482             }
1483         }
1484 
1485         unum_formatInt64(fmt, U_INT64_MIN, result, 512, NULL, &status);
1486         if (U_FAILURE(status)) {
1487             log_err("error in unum_format(): %s\n", myErrorName(status));
1488         } else {
1489             log_verbose("format int64min: '%s'\n", result);
1490             parsepos = 0;
1491             val32 = unum_parse(fmt, result, u_strlen(result), &parsepos, &status);
1492             if (status != U_INVALID_FORMAT_ERROR) {
1493                 log_err("parse didn't report error: %s\n", myErrorName(status));
1494             } else if (val32 != INT32_MIN) {
1495                 log_err("parse didn't pin return value, got: %d\n", val32);
1496             }
1497 
1498             status = U_ZERO_ERROR;
1499             parsepos = 0;
1500             val64 = unum_parseInt64(fmt, result, u_strlen(result), &parsepos, &status);
1501             if (U_FAILURE(status)) {
1502                 log_err("parseInt64 returned error: %s\n", myErrorName(status));
1503             } else if (val64 != U_INT64_MIN) {
1504                 log_err("parseInt64 returned incorrect value, got: %ld\n", val64);
1505             }
1506 
1507             status = U_ZERO_ERROR;
1508             parsepos = 0;
1509             valDouble = unum_parseDouble(fmt, result, u_strlen(result), &parsepos, &status);
1510             if (U_FAILURE(status)) {
1511                 log_err("parseDouble returned error: %s\n", myErrorName(status));
1512             } else if (valDouble != doubleInt64Min) {
1513                 log_err("parseDouble returned incorrect value, got: %g\n", valDouble);
1514             }
1515         }
1516 
1517         unum_formatDouble(fmt, doubleBig, result, 512, NULL, &status);
1518         if (U_FAILURE(status)) {
1519             log_err("error in unum_format(): %s\n", myErrorName(status));
1520         } else {
1521             log_verbose("format doubleBig: '%s'\n", result);
1522             parsepos = 0;
1523             val32 = unum_parse(fmt, result, u_strlen(result), &parsepos, &status);
1524             if (status != U_INVALID_FORMAT_ERROR) {
1525                 log_err("parse didn't report error: %s\n", myErrorName(status));
1526             } else if (val32 != INT32_MAX) {
1527                 log_err("parse didn't pin return value, got: %d\n", val32);
1528             }
1529 
1530             status = U_ZERO_ERROR;
1531             parsepos = 0;
1532             val64 = unum_parseInt64(fmt, result, u_strlen(result), &parsepos, &status);
1533             if (status != U_INVALID_FORMAT_ERROR) {
1534                 log_err("parseInt64 didn't report error error: %s\n", myErrorName(status));
1535             } else if (val64 != U_INT64_MAX) {
1536                 log_err("parseInt64 returned incorrect value, got: %ld\n", val64);
1537             }
1538 
1539             status = U_ZERO_ERROR;
1540             parsepos = 0;
1541             valDouble = unum_parseDouble(fmt, result, u_strlen(result), &parsepos, &status);
1542             if (U_FAILURE(status)) {
1543                 log_err("parseDouble returned error: %s\n", myErrorName(status));
1544             } else if (!withinErr(valDouble, doubleBig, 1e-15)) {
1545                 log_err("parseDouble returned incorrect value, got: %g\n", valDouble);
1546             }
1547         }
1548 
1549         u_uastrcpy(result, "5.06e-27");
1550         parsepos = 0;
1551         valDouble = unum_parseDouble(fmt, result, u_strlen(result), &parsepos, &status);
1552         if (U_FAILURE(status)) {
1553             log_err("parseDouble() returned error: %s\n", myErrorName(status));
1554         } else if (!withinErr(valDouble, 5.06e-27, 1e-15)) {
1555             log_err("parseDouble() returned incorrect value, got: %g\n", valDouble);
1556         }
1557     }
1558     unum_close(fmt);
1559 }
1560 
1561 
test_fmt(UNumberFormat * fmt,UBool isDecimal)1562 static void test_fmt(UNumberFormat* fmt, UBool isDecimal) {
1563     char temp[512];
1564     UChar buffer[512];
1565     int32_t BUFSIZE = UPRV_LENGTHOF(buffer);
1566     double vals[] = {
1567         -.2, 0, .2, 5.5, 15.2, 250, 123456789
1568     };
1569     int i;
1570 
1571     for (i = 0; i < UPRV_LENGTHOF(vals); ++i) {
1572         UErrorCode status = U_ZERO_ERROR;
1573         unum_formatDouble(fmt, vals[i], buffer, BUFSIZE, NULL, &status);
1574         if (U_FAILURE(status)) {
1575             log_err("failed to format: %g, returned %s\n", vals[i], u_errorName(status));
1576         } else {
1577             u_austrcpy(temp, buffer);
1578             log_verbose("formatting %g returned '%s'\n", vals[i], temp);
1579         }
1580     }
1581 
1582     /* check APIs now */
1583     {
1584         UErrorCode status = U_ZERO_ERROR;
1585         UParseError perr;
1586         u_uastrcpy(buffer, "#,##0.0#");
1587         unum_applyPattern(fmt, false, buffer, -1, &perr, &status);
1588         if (isDecimal ? U_FAILURE(status) : (status != U_UNSUPPORTED_ERROR)) {
1589             log_err("got unexpected error for applyPattern: '%s'\n", u_errorName(status));
1590         }
1591     }
1592 
1593     {
1594         int isLenient = unum_getAttribute(fmt, UNUM_LENIENT_PARSE);
1595         log_verbose("lenient: 0x%x\n", isLenient);
1596         if (isLenient != false) {
1597             log_err("didn't expect lenient value: %d\n", isLenient);
1598         }
1599 
1600         unum_setAttribute(fmt, UNUM_LENIENT_PARSE, true);
1601         isLenient = unum_getAttribute(fmt, UNUM_LENIENT_PARSE);
1602         if (isLenient != true) {
1603             log_err("didn't expect lenient value after set: %d\n", isLenient);
1604         }
1605     }
1606 
1607     {
1608         double val2;
1609         double val = unum_getDoubleAttribute(fmt, UNUM_LENIENT_PARSE);
1610         if (val != -1) {
1611             log_err("didn't expect double attribute\n");
1612         }
1613         val = unum_getDoubleAttribute(fmt, UNUM_ROUNDING_INCREMENT);
1614         if ((val == -1) == isDecimal) {
1615             log_err("didn't expect -1 rounding increment\n");
1616         }
1617         unum_setDoubleAttribute(fmt, UNUM_ROUNDING_INCREMENT, val+.5);
1618         val2 = unum_getDoubleAttribute(fmt, UNUM_ROUNDING_INCREMENT);
1619         if (isDecimal && (val2 - val != .5)) {
1620             log_err("set rounding increment had no effect on decimal format");
1621         }
1622     }
1623 
1624     {
1625         UErrorCode status = U_ZERO_ERROR;
1626         int len = unum_getTextAttribute(fmt, UNUM_DEFAULT_RULESET, buffer, BUFSIZE, &status);
1627         if (isDecimal ? (status != U_UNSUPPORTED_ERROR) : U_FAILURE(status)) {
1628             log_err("got unexpected error for get default ruleset: '%s'\n", u_errorName(status));
1629         }
1630         if (U_SUCCESS(status)) {
1631             u_austrcpy(temp, buffer);
1632             log_verbose("default ruleset: '%s'\n", temp);
1633         }
1634 
1635         status = U_ZERO_ERROR;
1636         len = unum_getTextAttribute(fmt, UNUM_PUBLIC_RULESETS, buffer, BUFSIZE, &status);
1637         if (isDecimal ? (status != U_UNSUPPORTED_ERROR) : U_FAILURE(status)) {
1638             log_err("got unexpected error for get public rulesets: '%s'\n", u_errorName(status));
1639         }
1640         if (U_SUCCESS(status)) {
1641             u_austrcpy(temp, buffer);
1642             log_verbose("public rulesets: '%s'\n", temp);
1643 
1644             /* set the default ruleset to the first one found, and retry */
1645 
1646             if (len > 0) {
1647                 for (i = 0; i < len && temp[i] != ';'; ++i){}
1648                 if (i < len) {
1649                     buffer[i] = 0;
1650                     unum_setTextAttribute(fmt, UNUM_DEFAULT_RULESET, buffer, -1, &status);
1651                     if (U_FAILURE(status)) {
1652                         log_err("unexpected error setting default ruleset: '%s'\n", u_errorName(status));
1653                     } else {
1654                         int len2 = unum_getTextAttribute(fmt, UNUM_DEFAULT_RULESET, buffer, BUFSIZE, &status);
1655                         if (U_FAILURE(status)) {
1656                             log_err("could not fetch default ruleset: '%s'\n", u_errorName(status));
1657                         } else if (len2 != i) {
1658                             u_austrcpy(temp, buffer);
1659                             log_err("unexpected ruleset len: %d ex: %d val: %s\n", len2, i, temp);
1660                         } else {
1661                             for (i = 0; i < UPRV_LENGTHOF(vals); ++i) {
1662                                 status = U_ZERO_ERROR;
1663                                 unum_formatDouble(fmt, vals[i], buffer, BUFSIZE, NULL, &status);
1664                                 if (U_FAILURE(status)) {
1665                                     log_err("failed to format: %g, returned %s\n", vals[i], u_errorName(status));
1666                                 } else {
1667                                     u_austrcpy(temp, buffer);
1668                                     log_verbose("formatting %g returned '%s'\n", vals[i], temp);
1669                                 }
1670                             }
1671                         }
1672                     }
1673                 }
1674             }
1675         }
1676     }
1677 
1678     {
1679         UErrorCode status = U_ZERO_ERROR;
1680         unum_toPattern(fmt, false, buffer, BUFSIZE, &status);
1681         if (U_SUCCESS(status)) {
1682             u_austrcpy(temp, buffer);
1683             log_verbose("pattern: '%s'\n", temp);
1684         } else if (status != U_BUFFER_OVERFLOW_ERROR) {
1685             log_err("toPattern failed unexpectedly: %s\n", u_errorName(status));
1686         } else {
1687             log_verbose("pattern too long to display\n");
1688         }
1689     }
1690 
1691     {
1692         UErrorCode status = U_ZERO_ERROR;
1693         int len = unum_getSymbol(fmt, UNUM_CURRENCY_SYMBOL, buffer, BUFSIZE, &status);
1694         if (isDecimal ? U_FAILURE(status) : (status != U_UNSUPPORTED_ERROR)) {
1695             log_err("unexpected error getting symbol: '%s'\n", u_errorName(status));
1696         }
1697 
1698         unum_setSymbol(fmt, UNUM_CURRENCY_SYMBOL, buffer, len, &status);
1699         if (isDecimal ? U_FAILURE(status) : (status != U_UNSUPPORTED_ERROR)) {
1700             log_err("unexpected error setting symbol: '%s'\n", u_errorName(status));
1701         }
1702     }
1703 }
1704 
TestNonExistentCurrency()1705 static void TestNonExistentCurrency() {
1706     UNumberFormat *format;
1707     UErrorCode status = U_ZERO_ERROR;
1708     UChar currencySymbol[8];
1709     static const UChar QQQ[] = {0x51, 0x51, 0x51, 0};
1710 
1711     /* Get a non-existent currency and make sure it returns the correct currency code. */
1712     format = unum_open(UNUM_CURRENCY, NULL, 0, "th_TH@currency=QQQ", NULL, &status);
1713     if (format == NULL || U_FAILURE(status)) {
1714         log_data_err("unum_open did not return expected result for non-existent requested currency: '%s' (Are you missing data?)\n", u_errorName(status));
1715     }
1716     else {
1717         unum_getSymbol(format,
1718                 UNUM_CURRENCY_SYMBOL,
1719                 currencySymbol,
1720                 UPRV_LENGTHOF(currencySymbol),
1721                 &status);
1722         if (u_strcmp(currencySymbol, QQQ) != 0) {
1723             log_err("unum_open set the currency to QQQ\n");
1724         }
1725     }
1726     unum_close(format);
1727 }
1728 
TestRBNFFormat()1729 static void TestRBNFFormat() {
1730     UErrorCode status;
1731     UParseError perr;
1732     UChar pat[1024];
1733     UChar tempUChars[512];
1734     UNumberFormat *formats[5];
1735     int COUNT = UPRV_LENGTHOF(formats);
1736     int i;
1737 
1738     for (i = 0; i < COUNT; ++i) {
1739         formats[i] = 0;
1740     }
1741 
1742     /* instantiation */
1743     status = U_ZERO_ERROR;
1744     u_uastrcpy(pat, "#,##0.0#;(#,##0.0#)");
1745     formats[0] = unum_open(UNUM_PATTERN_DECIMAL, pat, -1, "en_US", &perr, &status);
1746     if (U_FAILURE(status)) {
1747         log_err_status(status, "unable to open decimal pattern -> %s\n", u_errorName(status));
1748         return;
1749     }
1750 
1751     status = U_ZERO_ERROR;
1752     formats[1] = unum_open(UNUM_SPELLOUT, NULL, 0, "en_US", &perr, &status);
1753     if (U_FAILURE(status)) {
1754         log_err_status(status, "unable to open spellout -> %s\n", u_errorName(status));
1755         return;
1756     }
1757 
1758     status = U_ZERO_ERROR;
1759     formats[2] = unum_open(UNUM_ORDINAL, NULL, 0, "en_US", &perr, &status);
1760     if (U_FAILURE(status)) {
1761         log_err_status(status, "unable to open ordinal -> %s\n", u_errorName(status));
1762         return;
1763     }
1764 
1765     status = U_ZERO_ERROR;
1766     formats[3] = unum_open(UNUM_DURATION, NULL, 0, "en_US", &perr, &status);
1767     if (U_FAILURE(status)) {
1768         log_err_status(status, "unable to open duration %s\n", u_errorName(status));
1769         return;
1770     }
1771 
1772     status = U_ZERO_ERROR;
1773     u_uastrcpy(pat,
1774         "%standard:\n"
1775         "-x: minus >>;\n"
1776         "x.x: << point >>;\n"
1777         "zero; one; two; three; four; five; six; seven; eight; nine;\n"
1778         "ten; eleven; twelve; thirteen; fourteen; fifteen; sixteen;\n"
1779         "seventeen; eighteen; nineteen;\n"
1780         "20: twenty[->>];\n"
1781         "30: thirty[->>];\n"
1782         "40: forty[->>];\n"
1783         "50: fifty[->>];\n"
1784         "60: sixty[->>];\n"
1785         "70: seventy[->>];\n"
1786         "80: eighty[->>];\n"
1787         "90: ninety[->>];\n"
1788         "100: =#,##0=;\n");
1789     u_uastrcpy(tempUChars,
1790         "%simple:\n"
1791         "=%standard=;\n"
1792         "20: twenty[ and change];\n"
1793         "30: thirty[ and change];\n"
1794         "40: forty[ and change];\n"
1795         "50: fifty[ and change];\n"
1796         "60: sixty[ and change];\n"
1797         "70: seventy[ and change];\n"
1798         "80: eighty[ and change];\n"
1799         "90: ninety[ and change];\n"
1800         "100: =#,##0=;\n"
1801         "%bogus:\n"
1802         "0.x: tiny;\n"
1803         "x.x: << point something;\n"
1804         "=%standard=;\n"
1805         "20: some reasonable number;\n"
1806         "100: some substantial number;\n"
1807         "100,000,000: some huge number;\n");
1808     /* This is to get around some compiler warnings about char * string length. */
1809     u_strcat(pat, tempUChars);
1810     formats[4] = unum_open(UNUM_PATTERN_RULEBASED, pat, -1, "en_US", &perr, &status);
1811     if (U_FAILURE(status)) {
1812         log_err_status(status, "unable to open rulebased pattern -> %s\n", u_errorName(status));
1813     }
1814     if (U_FAILURE(status)) {
1815         log_err_status(status, "Something failed with %s\n", u_errorName(status));
1816         return;
1817     }
1818 
1819     for (i = 0; i < COUNT; ++i) {
1820         log_verbose("\n\ntesting format %d\n", i);
1821         test_fmt(formats[i], (UBool)(i == 0));
1822     }
1823 
1824     #define FORMAT_BUF_CAPACITY 64
1825     {
1826         UChar fmtbuf[FORMAT_BUF_CAPACITY];
1827         int32_t len;
1828         double nanvalue = uprv_getNaN();
1829         status = U_ZERO_ERROR;
1830         len = unum_formatDouble(formats[1], nanvalue, fmtbuf, FORMAT_BUF_CAPACITY, NULL, &status);
1831         if (U_FAILURE(status)) {
1832             log_err_status(status, "unum_formatDouble NAN failed with %s\n", u_errorName(status));
1833         } else {
1834             UChar nansym[] = { 0x4E, 0x61, 0x4E, 0 }; /* NaN */
1835             if ( len != 3 || u_strcmp(fmtbuf, nansym) != 0 ) {
1836                 log_err("unum_formatDouble NAN produced wrong answer for en_US\n");
1837             }
1838         }
1839     }
1840 
1841     for (i = 0; i < COUNT; ++i) {
1842         unum_close(formats[i]);
1843     }
1844 }
1845 
TestRBNFRounding()1846 static void TestRBNFRounding() {
1847     UChar fmtbuf[FORMAT_BUF_CAPACITY];
1848     UChar expectedBuf[FORMAT_BUF_CAPACITY];
1849     int32_t len;
1850     UErrorCode status = U_ZERO_ERROR;
1851     UNumberFormat* fmt = unum_open(UNUM_SPELLOUT, NULL, 0, "en_US", NULL, &status);
1852     if (U_FAILURE(status)) {
1853         log_err_status(status, "unable to open spellout -> %s\n", u_errorName(status));
1854         return;
1855     }
1856     len = unum_formatDouble(fmt, 10.123456789, fmtbuf, FORMAT_BUF_CAPACITY, NULL, &status);
1857     U_ASSERT(len < FORMAT_BUF_CAPACITY);
1858     (void)len;
1859     if (U_FAILURE(status)) {
1860         log_err_status(status, "unum_formatDouble 10.123456789 failed with %s\n", u_errorName(status));
1861     }
1862     u_uastrcpy(expectedBuf, "ten point one two three four five six seven eight nine");
1863     if (u_strcmp(expectedBuf, fmtbuf) != 0) {
1864         log_err("Wrong result for unrounded value\n");
1865     }
1866     unum_setAttribute(fmt, UNUM_MAX_FRACTION_DIGITS, 3);
1867     if (unum_getAttribute(fmt, UNUM_MAX_FRACTION_DIGITS) != 3) {
1868         log_err("UNUM_MAX_FRACTION_DIGITS was incorrectly ignored -> %d\n", unum_getAttribute(fmt, UNUM_MAX_FRACTION_DIGITS));
1869     }
1870     if (unum_getAttribute(fmt, UNUM_ROUNDING_MODE) != UNUM_ROUND_UNNECESSARY) {
1871         log_err("UNUM_ROUNDING_MODE was set -> %d\n", unum_getAttribute(fmt, UNUM_ROUNDING_MODE));
1872     }
1873     unum_setAttribute(fmt, UNUM_ROUNDING_MODE, UNUM_ROUND_HALFUP);
1874     if (unum_getAttribute(fmt, UNUM_ROUNDING_MODE) != UNUM_ROUND_HALFUP) {
1875         log_err("UNUM_ROUNDING_MODE was not set -> %d\n", unum_getAttribute(fmt, UNUM_ROUNDING_MODE));
1876     }
1877     len = unum_formatDouble(fmt, 10.123456789, fmtbuf, FORMAT_BUF_CAPACITY, NULL, &status);
1878     U_ASSERT(len < FORMAT_BUF_CAPACITY);
1879     if (U_FAILURE(status)) {
1880         log_err_status(status, "unum_formatDouble 10.123456789 failed with %s\n", u_errorName(status));
1881     }
1882     u_uastrcpy(expectedBuf, "ten point one two three");
1883     if (u_strcmp(expectedBuf, fmtbuf) != 0) {
1884         char temp[512];
1885         u_austrcpy(temp, fmtbuf);
1886         log_err("Wrong result for rounded value. Got: %s\n", temp);
1887     }
1888     unum_close(fmt);
1889 }
1890 
TestCurrencyRegression(void)1891 static void TestCurrencyRegression(void) {
1892 /*
1893  I've found a case where unum_parseDoubleCurrency is not doing what I
1894 expect.  The value I pass in is $1234567890q123460000.00 and this
1895 returns with a status of zero error & a parse pos of 22 (I would
1896 expect a parse error at position 11).
1897 
1898 I stepped into DecimalFormat::subparse() and it looks like it parses
1899 the first 10 digits and then stops parsing at the q but doesn't set an
1900 error. Then later in DecimalFormat::parse() the value gets crammed
1901 into a long (which greatly truncates the value).
1902 
1903 This is very problematic for me 'cause I try to remove chars that are
1904 invalid but this allows my users to enter bad chars and truncates
1905 their data!
1906 */
1907 
1908     UChar buf[1024];
1909     UChar currency[8];
1910     char acurrency[16];
1911     double d;
1912     UNumberFormat *cur;
1913     int32_t pos;
1914     UErrorCode status  = U_ZERO_ERROR;
1915     const int32_t expected = 11;
1916 
1917     currency[0]=0;
1918     u_uastrcpy(buf, "$1234567890q643210000.00");
1919     cur = unum_open(UNUM_CURRENCY, NULL,0,"en_US", NULL, &status);
1920 
1921     if(U_FAILURE(status)) {
1922         log_data_err("unum_open failed: %s (Are you missing data?)\n", u_errorName(status));
1923         return;
1924     }
1925 
1926     status = U_ZERO_ERROR; /* so we can test it later. */
1927     pos = 0;
1928 
1929     d = unum_parseDoubleCurrency(cur,
1930                          buf,
1931                          -1,
1932                          &pos, /* 0 = start */
1933                          currency,
1934                          &status);
1935 
1936     u_austrcpy(acurrency, currency);
1937 
1938     if(U_FAILURE(status) || (pos != expected)) {
1939         log_err("unum_parseDoubleCurrency should have failed with pos %d, but gave: value %.9f, err %s, pos=%d, currency [%s]\n",
1940             expected, d, u_errorName(status), pos, acurrency);
1941     } else {
1942         log_verbose("unum_parseDoubleCurrency failed, value %.9f err %s, pos %d, currency [%s]\n", d, u_errorName(status), pos, acurrency);
1943     }
1944 
1945     unum_close(cur);
1946 }
1947 
TestTextAttributeCrash(void)1948 static void TestTextAttributeCrash(void) {
1949     UChar ubuffer[64] = {0x0049,0x004E,0x0052,0};
1950     static const UChar expectedNeg[] = {0x0049,0x004E,0x0052,0x0031,0x0032,0x0033,0x0034,0x002E,0x0035,0};
1951     static const UChar expectedPos[] = {0x0031,0x0032,0x0033,0x0034,0x002E,0x0035,0};
1952     int32_t used;
1953     UErrorCode status = U_ZERO_ERROR;
1954     UNumberFormat *nf = unum_open(UNUM_CURRENCY, NULL, 0, "en_US", NULL, &status);
1955     if (U_FAILURE(status)) {
1956         log_data_err("FAILED 1 -> %s (Are you missing data?)\n", u_errorName(status));
1957         return;
1958     }
1959     unum_setTextAttribute(nf, UNUM_CURRENCY_CODE, ubuffer, 3, &status);
1960     /*
1961      * the usual negative prefix and suffix seem to be '($' and ')' at this point
1962      * also crashes if UNUM_NEGATIVE_SUFFIX is substituted for UNUM_NEGATIVE_PREFIX here
1963      */
1964     used = unum_getTextAttribute(nf, UNUM_NEGATIVE_PREFIX, ubuffer, 64, &status);
1965     unum_setTextAttribute(nf, UNUM_NEGATIVE_PREFIX, ubuffer, used, &status);
1966     if (U_FAILURE(status)) {
1967         log_err("FAILED 2\n"); exit(1);
1968     }
1969     log_verbose("attempting to format...\n");
1970     used = unum_formatDouble(nf, -1234.5, ubuffer, 64, NULL, &status);
1971     if (U_FAILURE(status) || 64 < used) {
1972         log_err("Failed formatting %s\n", u_errorName(status));
1973         return;
1974     }
1975     if (u_strcmp(expectedNeg, ubuffer) == 0) {
1976         log_err("Didn't get expected negative result\n");
1977     }
1978     used = unum_formatDouble(nf, 1234.5, ubuffer, 64, NULL, &status);
1979     if (U_FAILURE(status) || 64 < used) {
1980         log_err("Failed formatting %s\n", u_errorName(status));
1981         return;
1982     }
1983     if (u_strcmp(expectedPos, ubuffer) == 0) {
1984         log_err("Didn't get expected positive result\n");
1985     }
1986     unum_close(nf);
1987 }
1988 
TestNBSPPatternRtNum(const char * testcase,int line,UNumberFormat * nf,double myNumber)1989 static void TestNBSPPatternRtNum(const char *testcase, int line, UNumberFormat *nf, double myNumber) {
1990     UErrorCode status = U_ZERO_ERROR;
1991     UChar myString[20];
1992     char tmpbuf[200];
1993     double aNumber = -1.0;
1994     unum_formatDouble(nf, myNumber, myString, 20, NULL, &status);
1995     log_verbose("%s:%d: formatted %.2f into %s\n", testcase, line, myNumber, u_austrcpy(tmpbuf, myString));
1996     if(U_FAILURE(status)) {
1997       log_err("%s:%d: failed format of %.2g with %s\n", testcase, line, myNumber, u_errorName(status));
1998         return;
1999     }
2000     aNumber = unum_parse(nf, myString, -1, NULL, &status);
2001     if(U_FAILURE(status)) {
2002       log_err("%s:%d: failed parse with %s\n", testcase, line, u_errorName(status));
2003         return;
2004     }
2005     if(uprv_fabs(aNumber-myNumber)>.001) {
2006       log_err("FAIL: %s:%d formatted %.2f, parsed into %.2f\n", testcase, line, myNumber, aNumber);
2007     } else {
2008       log_verbose("PASS: %s:%d formatted %.2f, parsed into %.2f\n", testcase, line, myNumber, aNumber);
2009     }
2010 }
2011 
TestNBSPPatternRT(const char * testcase,UNumberFormat * nf)2012 static void TestNBSPPatternRT(const char *testcase, UNumberFormat *nf) {
2013   TestNBSPPatternRtNum(testcase, __LINE__, nf, 12345.);
2014   TestNBSPPatternRtNum(testcase, __LINE__, nf, -12345.);
2015 }
2016 
TestNBSPInPattern(void)2017 static void TestNBSPInPattern(void) {
2018     UErrorCode status = U_ZERO_ERROR;
2019     UNumberFormat* nf = NULL;
2020     const char *testcase;
2021 
2022 
2023     testcase="ar_AE UNUM_CURRENCY";
2024     nf  = unum_open(UNUM_CURRENCY, NULL, -1, "ar_AE", NULL, &status);
2025     if(U_FAILURE(status) || nf == NULL) {
2026       log_data_err("%s:%d: %s: unum_open failed with %s (Are you missing data?)\n", __FILE__, __LINE__, testcase, u_errorName(status));
2027         return;
2028     }
2029     TestNBSPPatternRT(testcase, nf);
2030 
2031     /* if we don't have CLDR 1.6 data, bring out the problem anyways */
2032     {
2033 #define SPECIAL_PATTERN "\\u00A4\\u00A4'\\u062f.\\u0625.\\u200f\\u00a0'###0.00"
2034         UChar pat[200];
2035         testcase = "ar_AE special pattern: " SPECIAL_PATTERN;
2036         u_unescape(SPECIAL_PATTERN, pat, UPRV_LENGTHOF(pat));
2037         unum_applyPattern(nf, false, pat, -1, NULL, &status);
2038         if(U_FAILURE(status)) {
2039             log_err("%s: unum_applyPattern failed with %s\n", testcase, u_errorName(status));
2040         } else {
2041             TestNBSPPatternRT(testcase, nf);
2042         }
2043 #undef SPECIAL_PATTERN
2044     }
2045     unum_close(nf); status = U_ZERO_ERROR;
2046 
2047     testcase="ar_AE UNUM_DECIMAL";
2048     nf  = unum_open(UNUM_DECIMAL, NULL, -1, "ar_AE", NULL, &status);
2049     if(U_FAILURE(status)) {
2050         log_err("%s: unum_open failed with %s\n", testcase, u_errorName(status));
2051     }
2052     TestNBSPPatternRT(testcase, nf);
2053     unum_close(nf); status = U_ZERO_ERROR;
2054 
2055     testcase="ar_AE UNUM_PERCENT";
2056     nf  = unum_open(UNUM_PERCENT, NULL, -1, "ar_AE", NULL, &status);
2057     if(U_FAILURE(status)) {
2058         log_err("%s: unum_open failed with %s\n", testcase, u_errorName(status));
2059     }
2060     TestNBSPPatternRT(testcase, nf);
2061     unum_close(nf); status = U_ZERO_ERROR;
2062 
2063 
2064 
2065 }
TestCloneWithRBNF(void)2066 static void TestCloneWithRBNF(void) {
2067     UChar pattern[1024];
2068     UChar pat2[512];
2069     UErrorCode status = U_ZERO_ERROR;
2070     UChar buffer[256];
2071     UChar buffer_cloned[256];
2072     char temp1[256];
2073     char temp2[256];
2074     UNumberFormat *pform_cloned;
2075     UNumberFormat *pform;
2076 
2077     u_uastrcpy(pattern,
2078         "%main:\n"
2079         "0.x: >%%millis-only>;\n"
2080         "x.0: <%%duration<;\n"
2081         "x.x: <%%durationwithmillis<>%%millis-added>;\n"
2082         "-x: ->>;%%millis-only:\n"
2083         "1000: 00:00.<%%millis<;\n"
2084         "%%millis-added:\n"
2085         "1000: .<%%millis<;\n"
2086         "%%millis:\n"
2087         "0: =000=;\n"
2088         "%%duration:\n"
2089         "0: =%%seconds-only=;\n"
2090         "60: =%%min-sec=;\n"
2091         "3600: =%%hr-min-sec=;\n"
2092         "86400/86400: <%%ddaayyss<[, >>];\n"
2093         "%%durationwithmillis:\n"
2094         "0: =%%seconds-only=;\n"
2095         "60: =%%min-sec=;\n"
2096         "3600: =%%hr-min-sec=;\n"
2097         "86400/86400: <%%ddaayyss<, >>;\n");
2098     u_uastrcpy(pat2,
2099         "%%seconds-only:\n"
2100         "0: 0:00:=00=;\n"
2101         "%%min-sec:\n"
2102         "0: :=00=;\n"
2103         "0/60: 0:<00<>>;\n"
2104         "%%hr-min-sec:\n"
2105         "0: :=00=;\n"
2106         "60/60: <00<>>;\n"
2107         "3600/60: <0<:>>>;\n"
2108         "%%ddaayyss:\n"
2109         "0 days;\n"
2110         "1 day;\n"
2111         "=0= days;");
2112 
2113     /* This is to get around some compiler warnings about char * string length. */
2114     u_strcat(pattern, pat2);
2115 
2116     pform = unum_open(UNUM_PATTERN_RULEBASED, pattern, -1, "en_US", NULL, &status);
2117     unum_formatDouble(pform, 3600, buffer, 256, NULL, &status);
2118 
2119     pform_cloned = unum_clone(pform,&status);
2120     unum_formatDouble(pform_cloned, 3600, buffer_cloned, 256, NULL, &status);
2121 
2122     unum_close(pform);
2123     unum_close(pform_cloned);
2124 
2125     if (u_strcmp(buffer,buffer_cloned)) {
2126         log_data_err("Result from cloned formatter not identical to the original. Original: %s Cloned: %s - (Are you missing data?)",u_austrcpy(temp1, buffer),u_austrcpy(temp2,buffer_cloned));
2127     }
2128 }
2129 
2130 
TestNoExponent(void)2131 static void TestNoExponent(void) {
2132     UErrorCode status = U_ZERO_ERROR;
2133     UChar str[100];
2134     const char *cstr;
2135     UNumberFormat *fmt;
2136     int32_t pos;
2137     int32_t expect = 0;
2138     int32_t num;
2139 
2140     fmt = unum_open(UNUM_DECIMAL, NULL, -1, "en_US", NULL, &status);
2141 
2142     if(U_FAILURE(status) || fmt == NULL) {
2143         log_data_err("%s:%d: unum_open failed with %s (Are you missing data?)\n", __FILE__, __LINE__, u_errorName(status));
2144         return;
2145     }
2146 
2147     cstr = "10E6";
2148     u_uastrcpy(str, cstr);
2149     expect = 10000000;
2150     pos = 0;
2151     num = unum_parse(fmt, str, -1, &pos, &status);
2152     ASSERT_TRUE(pos==4);
2153     if(U_FAILURE(status)) {
2154         log_data_err("%s:%d: unum_parse failed with %s for %s (Are you missing data?)\n", __FILE__, __LINE__, u_errorName(status), cstr);
2155     } else if(expect!=num) {
2156         log_data_err("%s:%d: unum_parse failed, got %d expected %d for '%s'(Are you missing data?)\n", __FILE__, __LINE__, num, expect, cstr);
2157     } else {
2158         log_verbose("%s:%d: unum_parse returned %d for '%s'\n", __FILE__, __LINE__, num, cstr);
2159     }
2160 
2161     ASSERT_TRUE(unum_getAttribute(fmt, UNUM_PARSE_NO_EXPONENT)==0);
2162 
2163     unum_setAttribute(fmt, UNUM_PARSE_NO_EXPONENT, 1); /* no error code */
2164     log_verbose("set UNUM_PARSE_NO_EXPONENT\n");
2165 
2166     ASSERT_TRUE(unum_getAttribute(fmt, UNUM_PARSE_NO_EXPONENT)==1);
2167 
2168     pos = 0;
2169     expect=10;
2170     num = unum_parse(fmt, str, -1, &pos, &status);
2171     if(num==10000000) {
2172         log_err("%s:%d: FAIL: unum_parse should have returned 10, not 10000000 on %s after UNUM_PARSE_NO_EXPONENT\n", __FILE__, __LINE__, cstr);
2173     } else if(num==expect) {
2174         log_verbose("%s:%d: unum_parse gave %d for %s - good.\n", __FILE__, __LINE__, num, cstr);
2175     }
2176     ASSERT_TRUE(pos==2);
2177 
2178     status = U_ZERO_ERROR;
2179 
2180     unum_close(fmt);
2181 
2182     /* ok, now try scientific */
2183     fmt = unum_open(UNUM_SCIENTIFIC, NULL, -1, "en_US", NULL, &status);
2184     assertSuccess("unum_open(UNUM_SCIENTIFIC, ...)", &status);
2185 
2186     ASSERT_TRUE(unum_getAttribute(fmt, UNUM_PARSE_NO_EXPONENT)==0);
2187 
2188     cstr = "10E6";
2189     u_uastrcpy(str, cstr);
2190     expect = 10000000;
2191     pos = 0;
2192     num = unum_parse(fmt, str, -1, &pos, &status);
2193     ASSERT_TRUE(pos==4);
2194     if(U_FAILURE(status)) {
2195         log_data_err("%s:%d: unum_parse failed with %s for %s (Are you missing data?)\n", __FILE__, __LINE__, u_errorName(status), cstr);
2196     } else if(expect!=num) {
2197         log_data_err("%s:%d: unum_parse failed, got %d expected %d for '%s'(Are you missing data?)\n", __FILE__, __LINE__, num, expect, cstr);
2198     } else {
2199         log_verbose("%s:%d: unum_parse returned %d for '%s'\n", __FILE__, __LINE__, num, cstr);
2200     }
2201 
2202     unum_setAttribute(fmt, UNUM_PARSE_NO_EXPONENT, 1); /* no error code */
2203     log_verbose("set UNUM_PARSE_NO_EXPONENT\n");
2204 
2205     ASSERT_TRUE(unum_getAttribute(fmt, UNUM_PARSE_NO_EXPONENT)==1);
2206 
2207     // A scientific formatter should parse the exponent even if UNUM_PARSE_NO_EXPONENT is set
2208     cstr = "10E6";
2209     u_uastrcpy(str, cstr);
2210     expect = 10000000;
2211     pos = 0;
2212     num = unum_parse(fmt, str, -1, &pos, &status);
2213     ASSERT_TRUE(pos==4);
2214     if(U_FAILURE(status)) {
2215         log_data_err("%s:%d: unum_parse failed with %s for %s (Are you missing data?)\n", __FILE__, __LINE__, u_errorName(status), cstr);
2216     } else if(expect!=num) {
2217         log_data_err("%s:%d: unum_parse failed, got %d expected %d for '%s'(Are you missing data?)\n", __FILE__, __LINE__, num, expect, cstr);
2218     } else {
2219         log_verbose("%s:%d: unum_parse returned %d for '%s'\n", __FILE__, __LINE__, num, cstr);
2220     }
2221 
2222     unum_close(fmt);
2223 }
2224 
TestMaxInt(void)2225 static void TestMaxInt(void) {
2226     UErrorCode status = U_ZERO_ERROR;
2227     UChar pattern_hash[] = { 0x23, 0x00 }; /* "#" */
2228     UChar result1[1024] = { 0 }, result2[1024] = { 0 };
2229     int32_t len1, len2;
2230     UChar expect[] = { 0x0039, 0x0037, 0 };
2231     UNumberFormat *fmt = unum_open(
2232                   UNUM_PATTERN_DECIMAL,      /* style         */
2233                   &pattern_hash[0],          /* pattern       */
2234                   u_strlen(pattern_hash),    /* patternLength */
2235                   "en",
2236                   0,                         /* parseErr      */
2237                   &status);
2238     if(U_FAILURE(status) || fmt == NULL) {
2239         log_data_err("%s:%d: %s: unum_open failed with %s (Are you missing data?)\n", __FILE__, __LINE__, "TestMaxInt", u_errorName(status));
2240         return;
2241     }
2242 
2243     unum_setAttribute(fmt, UNUM_MAX_INTEGER_DIGITS, 2);
2244 
2245     status = U_ZERO_ERROR;
2246     /* #1 */
2247     len1 = unum_formatInt64(fmt, 1997, result1, 1024, NULL, &status);
2248     result1[len1]=0;
2249     if(U_FAILURE(status) || u_strcmp(expect, result1)) {
2250         log_err("unum_formatInt64 Expected %s but got %s status %s\n", austrdup(expect), austrdup(result1), u_errorName(status));
2251     }
2252 
2253     status = U_ZERO_ERROR;
2254     /* #2 */
2255     len2 = unum_formatDouble(fmt, 1997.0, result2, 1024, NULL, &status);
2256     result2[len2]=0;
2257     if(U_FAILURE(status) || u_strcmp(expect, result2)) {
2258         log_err("unum_formatDouble Expected %s but got %s status %s\n", austrdup(expect), austrdup(result2), u_errorName(status));
2259     }
2260 
2261 
2262 
2263     /* test UNUM_FORMAT_FAIL_IF_MORE_THAN_MAX_DIGITS */
2264     ASSERT_TRUE(unum_getAttribute(fmt, UNUM_FORMAT_FAIL_IF_MORE_THAN_MAX_DIGITS)==0);
2265 
2266     unum_setAttribute(fmt, UNUM_FORMAT_FAIL_IF_MORE_THAN_MAX_DIGITS, 1);
2267     /* test UNUM_FORMAT_FAIL_IF_MORE_THAN_MAX_DIGITS */
2268     ASSERT_TRUE(unum_getAttribute(fmt, UNUM_FORMAT_FAIL_IF_MORE_THAN_MAX_DIGITS)==1);
2269 
2270     status = U_ZERO_ERROR;
2271     /* max int digits still '2' */
2272     len1 = unum_formatInt64(fmt, 1997, result1, 1024, NULL, &status);
2273     ASSERT_TRUE(status==U_ILLEGAL_ARGUMENT_ERROR);
2274     status = U_ZERO_ERROR;
2275 
2276     /* But, formatting 97->'97' works fine. */
2277 
2278     /* #1 */
2279     len1 = unum_formatInt64(fmt, 97, result1, 1024, NULL, &status);
2280     result1[len1]=0;
2281     if(U_FAILURE(status) || u_strcmp(expect, result1)) {
2282         log_err("unum_formatInt64 Expected %s but got %s status %s\n", austrdup(expect), austrdup(result1), u_errorName(status));
2283     }
2284 
2285     status = U_ZERO_ERROR;
2286     /* #2 */
2287     len2 = unum_formatDouble(fmt, 97.0, result2, 1024, NULL, &status);
2288     result2[len2]=0;
2289     if(U_FAILURE(status) || u_strcmp(expect, result2)) {
2290         log_err("unum_formatDouble Expected %s but got %s status %s\n", austrdup(expect), austrdup(result2), u_errorName(status));
2291     }
2292 
2293 
2294     unum_close(fmt);
2295 }
2296 
TestSignAlwaysShown(void)2297 static void TestSignAlwaysShown(void) {
2298     UErrorCode status = U_ZERO_ERROR;
2299     UNumberFormat *fmt = unum_open(
2300                   UNUM_DECIMAL, /* style         */
2301                   NULL,         /* pattern       */
2302                   0,            /* patternLength */
2303                   "en-US",
2304                   NULL,         /* parseErr      */
2305                   &status);
2306     assertSuccess("Creating UNumberFormat", &status);
2307     unum_setAttribute(fmt, UNUM_SIGN_ALWAYS_SHOWN, 1);
2308     UChar result[100];
2309     unum_formatDouble(fmt, 42, result, 100, NULL, &status);
2310     assertSuccess("Formatting with UNumberFormat", &status);
2311     assertUEquals("Result with sign always shown", u"+42", result);
2312     unum_close(fmt);
2313 }
2314 
TestMinimumGroupingDigits(void)2315 static void TestMinimumGroupingDigits(void) {
2316     UErrorCode status = U_ZERO_ERROR;
2317     UNumberFormat *fmt = unum_open(
2318                   UNUM_DECIMAL, /* style         */
2319                   NULL,         /* pattern       */
2320                   0,            /* patternLength */
2321                   "en-US",
2322                   NULL,         /* parseErr      */
2323                   &status);
2324     assertSuccess("Creating UNumberFormat", &status);
2325     unum_setAttribute(fmt, UNUM_MINIMUM_GROUPING_DIGITS, 2);
2326     UChar result[100];
2327     unum_formatDouble(fmt, 1234, result, 100, NULL, &status);
2328     assertSuccess("Formatting with UNumberFormat A", &status);
2329     assertUEquals("Result with minimum grouping digits A", u"1234", result);
2330     unum_formatDouble(fmt, 12345, result, 100, NULL, &status);
2331     assertSuccess("Formatting with UNumberFormat B", &status);
2332     assertUEquals("Result with minimum grouping digits B", u"12,345", result);
2333     unum_close(fmt);
2334 }
2335 
TestParseCaseSensitive(void)2336 static void TestParseCaseSensitive(void) {
2337     UErrorCode status = U_ZERO_ERROR;
2338     UNumberFormat *fmt = unum_open(
2339                   UNUM_DECIMAL, /* style         */
2340                   NULL,         /* pattern       */
2341                   0,            /* patternLength */
2342                   "en-US",
2343                   NULL,         /* parseErr      */
2344                   &status);
2345     assertSuccess("Creating UNumberFormat", &status);
2346     double result = unum_parseDouble(fmt, u"1e2", -1, NULL, &status);
2347     assertSuccess("Parsing with UNumberFormat, case insensitive", &status);
2348     assertIntEquals("Result with case sensitive", 100, (int64_t)result);
2349     unum_setAttribute(fmt, UNUM_PARSE_CASE_SENSITIVE, 1);
2350     int32_t ppos = 0;
2351     result = unum_parseDouble(fmt, u"1e2", -1, &ppos, &status);
2352     assertSuccess("Parsing with UNumberFormat, case sensitive", &status);
2353     assertIntEquals("Position with case sensitive", 1, ppos);
2354     assertIntEquals("Result with case sensitive", 1, (int64_t)result);
2355     unum_close(fmt);
2356 }
2357 
TestUFormattable(void)2358 static void TestUFormattable(void) {
2359   UChar out2k[2048];
2360   // simple test for API docs
2361   {
2362     UErrorCode status = U_ZERO_ERROR;
2363     UNumberFormat *unum = unum_open(UNUM_DEFAULT, NULL, -1, "en_US_POSIX", NULL, &status);
2364     if(assertSuccessCheck("calling unum_open()", &status, true)) {
2365       //! [unum_parseToUFormattable]
2366       const UChar str[] = { 0x0031, 0x0032, 0x0033, 0x0000 }; /* 123 */
2367       int32_t result = 0;
2368       UFormattable *ufmt = ufmt_open(&status);
2369       unum_parseToUFormattable(unum, ufmt, str, -1, NULL, &status);
2370       if (ufmt_isNumeric(ufmt)) {
2371           result = ufmt_getLong(ufmt, &status); /* == 123 */
2372       } /* else { ... } */
2373       ufmt_close(ufmt);
2374       //! [unum_parseToUFormattable]
2375       assertTrue("result == 123", (result == 123));
2376     }
2377     unum_close(unum);
2378   }
2379   // test with explicitly created ufmt_open
2380   {
2381     UChar buffer[2048];
2382     UErrorCode status = U_ZERO_ERROR;
2383     UFormattable *ufmt;
2384     UNumberFormat *unum;
2385     const char *pattern = "";
2386 
2387     ufmt = ufmt_open(&status);
2388     unum = unum_open(UNUM_DEFAULT, NULL, -1, "en_US_POSIX", NULL, &status);
2389     if(assertSuccessCheck("calling ufmt_open() || unum_open()", &status, true)) {
2390 
2391       pattern = "31337";
2392       log_verbose("-- pattern: %s\n", pattern);
2393       u_uastrcpy(buffer, pattern);
2394       unum_parseToUFormattable(unum, ufmt, buffer, -1, NULL, &status);
2395       if(assertSuccess("unum_parseToUFormattable(31337)", &status)) {
2396         assertTrue("ufmt_getLong()=31337", ufmt_getLong(ufmt, &status) == 31337);
2397         assertTrue("ufmt_getType()=UFMT_LONG", ufmt_getType(ufmt, &status) == UFMT_LONG);
2398         log_verbose("long = %d\n", ufmt_getLong(ufmt, &status));
2399         assertSuccess("ufmt_getLong()", &status);
2400       }
2401       unum_formatUFormattable(unum, ufmt, out2k, 2048, NULL, &status);
2402       if(assertSuccess("unum_formatUFormattable(31337)", &status)) {
2403         assertEquals("unum_formatUFormattable r/t", austrdup(buffer), austrdup(out2k));
2404       }
2405 
2406       pattern = "3.14159";
2407       log_verbose("-- pattern: %s\n", pattern);
2408       u_uastrcpy(buffer, pattern);
2409       unum_parseToUFormattable(unum, ufmt, buffer, -1, NULL, &status);
2410       if(assertSuccess("unum_parseToUFormattable(3.14159)", &status)) {
2411         assertTrue("ufmt_getDouble()==3.14159", withinErr(ufmt_getDouble(ufmt, &status), 3.14159, 1e-15));
2412         assertSuccess("ufmt_getDouble()", &status);
2413         assertTrue("ufmt_getType()=UFMT_DOUBLE", ufmt_getType(ufmt, &status) == UFMT_DOUBLE);
2414         log_verbose("double = %g\n", ufmt_getDouble(ufmt, &status));
2415       }
2416       unum_formatUFormattable(unum, ufmt, out2k, 2048, NULL, &status);
2417       if(assertSuccess("unum_formatUFormattable(3.14159)", &status)) {
2418         assertEquals("unum_formatUFormattable r/t", austrdup(buffer), austrdup(out2k));
2419       }
2420     }
2421     ufmt_close(ufmt);
2422     unum_close(unum);
2423   }
2424 
2425   // test with auto-generated ufmt
2426   {
2427     UChar buffer[2048];
2428     UErrorCode status = U_ZERO_ERROR;
2429     UFormattable *ufmt = NULL;
2430     UNumberFormat *unum;
2431     const char *pattern = "73476730924573500000000"; // weight of the moon, kg
2432 
2433     log_verbose("-- pattern: %s (testing auto-opened UFormattable)\n", pattern);
2434     u_uastrcpy(buffer, pattern);
2435 
2436     unum = unum_open(UNUM_DEFAULT, NULL, -1, "en_US_POSIX", NULL, &status);
2437     if(assertSuccessCheck("calling unum_open()", &status, true)) {
2438 
2439       ufmt = unum_parseToUFormattable(unum, NULL, /* will be ufmt_open()'ed for us */
2440                                    buffer, -1, NULL, &status);
2441       if(assertSuccess("unum_parseToUFormattable(weight of the moon)", &status)) {
2442         log_verbose("new formattable allocated at %p\n", (void*)ufmt);
2443         assertTrue("ufmt_isNumeric() true", ufmt_isNumeric(ufmt));
2444         unum_formatUFormattable(unum, ufmt, out2k, 2048, NULL, &status);
2445         if(assertSuccess("unum_formatUFormattable(3.14159)", &status)) {
2446           assertEquals("unum_formatUFormattable r/t", austrdup(buffer), austrdup(out2k));
2447         }
2448 
2449         log_verbose("double: %g\n",  ufmt_getDouble(ufmt, &status));
2450         assertSuccess("ufmt_getDouble()", &status);
2451 
2452         log_verbose("long: %ld\n", ufmt_getLong(ufmt, &status));
2453         assertTrue("failure on ufmt_getLong() for huge number:", U_FAILURE(status));
2454         // status is now a failure due to ufmt_getLong() above.
2455         // the intltest does extensive r/t testing of Formattable vs. UFormattable.
2456       }
2457     }
2458 
2459     unum_close(unum);
2460     ufmt_close(ufmt); // was implicitly opened for us by the first unum_parseToUFormattable()
2461   }
2462 }
2463 
2464 typedef struct {
2465     const char*  locale;
2466     const char*  numsys;
2467     int32_t      radix;
2468     UBool        isAlgorithmic;
2469     const UChar* description;
2470 } NumSysTestItem;
2471 
2472 
2473 static const UChar latnDesc[]    = {0x0030,0x0031,0x0032,0x0033,0x0034,0x0035,0x0036,0x0037,0x0038,0x0039,0}; // 0123456789
2474 static const UChar romanDesc[]   = {0x25,0x72,0x6F,0x6D,0x61,0x6E,0x2D,0x75,0x70,0x70,0x65,0x72,0}; // %roman-upper
2475 static const UChar arabDesc[]    = {0x0660,0x0661,0x0662,0x0663,0x0664,0x0665,0x0666,0x0667,0x0668,0x0669,0}; //
2476 static const UChar arabextDesc[] = {0x06F0,0x06F1,0x06F2,0x06F3,0x06F4,0x06F5,0x06F6,0x06F7,0x06F8,0x06F9,0}; //
2477 static const UChar hanidecDesc[] = {0x3007,0x4E00,0x4E8C,0x4E09,0x56DB,0x4E94,0x516D,0x4E03,0x516B,0x4E5D,0}; //
2478 static const UChar hantDesc[]    = {0x7A,0x68,0x5F,0x48,0x61,0x6E,0x74,0x2F,0x53,0x70,0x65,0x6C,0x6C,0x6F,0x75,0x74,
2479                                     0x52,0x75,0x6C,0x65,0x73,0x2F,0x25,0x73,0x70,0x65,0x6C,0x6C,0x6F,0x75,0x74,0x2D,
2480                                     0x63,0x61,0x72,0x64,0x69,0x6E,0x61,0x6C,0}; // zh_Hant/SpelloutRules/%spellout-cardinal
2481 
2482 static const NumSysTestItem numSysTestItems[] = {
2483     //locale                         numsys    radix isAlgo  description
2484     { "en",                          "latn",    10,  false,  latnDesc },
2485     { "en@numbers=roman",            "roman",   10,  true,   romanDesc },
2486     { "en@numbers=finance",          "latn",    10,  false,  latnDesc },
2487     { "ar-EG",                       "arab",    10,  false,  arabDesc },
2488     { "fa",                          "arabext", 10,  false,  arabextDesc },
2489     { "zh_Hans@numbers=hanidec",     "hanidec", 10,  false,  hanidecDesc },
2490     { "zh_Hant@numbers=traditional", "hant",    10,  true,   hantDesc },
2491     { NULL,                          NULL,       0,  false,  NULL },
2492 };
2493 enum { kNumSysDescripBufMax = 64 };
2494 
TestUNumberingSystem(void)2495 static void TestUNumberingSystem(void) {
2496     const NumSysTestItem * itemPtr;
2497     UNumberingSystem * unumsys;
2498     UEnumeration * uenum;
2499     const char * numsys;
2500     UErrorCode status;
2501 
2502     for (itemPtr = numSysTestItems; itemPtr->locale != NULL; itemPtr++) {
2503         status = U_ZERO_ERROR;
2504         unumsys = unumsys_open(itemPtr->locale, &status);
2505         if ( U_SUCCESS(status) ) {
2506             UChar ubuf[kNumSysDescripBufMax];
2507             int32_t ulen, radix = unumsys_getRadix(unumsys);
2508             UBool isAlgorithmic = unumsys_isAlgorithmic(unumsys);
2509             numsys = unumsys_getName(unumsys);
2510             if ( uprv_strcmp(numsys, itemPtr->numsys) != 0 || radix != itemPtr->radix || !isAlgorithmic != !itemPtr->isAlgorithmic ) {
2511                 log_data_err("unumsys name/radix/isAlgorithmic for locale %s, expected %s/%d/%d, got %s/%d/%d\n",
2512                         itemPtr->locale, itemPtr->numsys, itemPtr->radix, itemPtr->isAlgorithmic, numsys, radix, isAlgorithmic);
2513             }
2514             ulen = unumsys_getDescription(unumsys, ubuf, kNumSysDescripBufMax, &status);
2515             (void)ulen;   // Suppress variable not used warning.
2516             if ( U_FAILURE(status) || u_strcmp(ubuf, itemPtr->description) != 0 ) {
2517                 log_data_err("unumsys description for locale %s, description unexpected and/or status %\n", myErrorName(status));
2518             }
2519             unumsys_close(unumsys);
2520         } else {
2521             log_data_err("unumsys_open for locale %s fails with status %s\n", itemPtr->locale, myErrorName(status));
2522         }
2523     }
2524 
2525     for (int i=0; i<3; ++i) {
2526         // Run the test of unumsys_openAvailableNames() multiple times.
2527         // Helps verify the management of the internal cache of the names.
2528         status = U_ZERO_ERROR;
2529         uenum = unumsys_openAvailableNames(&status);
2530         if ( U_SUCCESS(status) ) {
2531             int32_t numsysCount = 0;
2532             // sanity check for a couple of number systems that must be in the enumeration
2533             UBool foundLatn = false;
2534             UBool foundArab = false;
2535             while ( (numsys = uenum_next(uenum, NULL, &status)) != NULL && U_SUCCESS(status) ) {
2536                 status = U_ZERO_ERROR;
2537                 unumsys = unumsys_openByName(numsys, &status);
2538                 if ( U_SUCCESS(status) ) {
2539                     numsysCount++;
2540                     if ( uprv_strcmp(numsys, "latn") ) foundLatn = true;
2541                     if ( uprv_strcmp(numsys, "arab") ) foundArab = true;
2542                     unumsys_close(unumsys);
2543                 } else {
2544                     log_err("unumsys_openAvailableNames includes %s but unumsys_openByName on it fails with status %s\n",
2545                             numsys, myErrorName(status));
2546                 }
2547             }
2548             uenum_close(uenum);
2549             if ( numsysCount < 40 || !foundLatn || !foundArab ) {
2550                 log_err("unumsys_openAvailableNames results incomplete: numsysCount %d, foundLatn %d, foundArab %d\n",
2551                         numsysCount, foundLatn, foundArab);
2552             }
2553         } else {
2554             log_data_err("unumsys_openAvailableNames fails with status %s\n", myErrorName(status));
2555         }
2556     }
2557 }
2558 
2559 /* plain-C version of test in numfmtst.cpp */
2560 enum { kUBufMax = 64 };
TestCurrencyIsoPluralFormat(void)2561 static void TestCurrencyIsoPluralFormat(void) {
2562     static const char* DATA[][8] = {
2563         // the data are:
2564         // locale,
2565         // currency amount to be formatted,
2566         // currency ISO code to be formatted,
2567         // format result using CURRENCYSTYLE,
2568         // format result using CURRENCY_STANDARD,
2569         // format result using CURRENCY_ACCOUNTING,
2570         // format result using ISOCURRENCYSTYLE,
2571         // format result using PLURALCURRENCYSTYLE,
2572 
2573         // locale             amount     ISOcode CURRENCYSTYLE         CURRENCY_STANDARD     CURRENCY_ACCOUNTING   ISOCURRENCYSTYLE          PLURALCURRENCYSTYLE
2574         {"en_US",             "1",        "USD", "$1.00",              "$1.00",              "$1.00",              "USD\\u00A01.00",        "1.00 US dollars"},
2575         {"en_US",             "1234.56",  "USD", "$1,234.56",          "$1,234.56",          "$1,234.56",          "USD\\u00A01,234.56",    "1,234.56 US dollars"},
2576         {"en_US@cf=account",  "1234.56",  "USD", "$1,234.56",          "$1,234.56",          "$1,234.56",          "USD\\u00A01,234.56",    "1,234.56 US dollars"},
2577         {"en_US",             "-1234.56", "USD", "-$1,234.56",         "-$1,234.56",         "($1,234.56)",        "-USD\\u00A01,234.56",   "-1,234.56 US dollars"},
2578         {"en_US@cf=account",  "-1234.56", "USD", "($1,234.56)",        "-$1,234.56",         "($1,234.56)",        "-USD\\u00A01,234.56",   "-1,234.56 US dollars"},
2579         {"en_US@cf=standard", "-1234.56", "USD", "-$1,234.56",         "-$1,234.56",         "($1,234.56)",        "-USD\\u00A01,234.56",   "-1,234.56 US dollars"},
2580         {"zh_CN",             "1",        "USD", "US$1.00",            "US$1.00",            "US$1.00",            "USD\\u00A01.00",        "1.00\\u00A0\\u7F8E\\u5143"},
2581         {"zh_CN",             "-1",       "USD", "-US$1.00",           "-US$1.00",           "(US$1.00)",          "-USD\\u00A01.00",       "-1.00\\u00A0\\u7F8E\\u5143"},
2582         {"zh_CN@cf=account",  "-1",       "USD", "(US$1.00)",          "-US$1.00",           "(US$1.00)",          "-USD\\u00A01.00",       "-1.00\\u00A0\\u7F8E\\u5143"},
2583         {"zh_CN@cf=standard", "-1",       "USD", "-US$1.00",           "-US$1.00",           "(US$1.00)",          "-USD\\u00A01.00",       "-1.00\\u00A0\\u7F8E\\u5143"},
2584         {"zh_CN",             "1234.56",  "USD", "US$1,234.56",        "US$1,234.56",        "US$1,234.56",        "USD\\u00A01,234.56",    "1,234.56\\u00A0\\u7F8E\\u5143"},
2585         // {"zh_CN",          "1",        "CHY", "CHY1.00",            "CHY1.00",            "CHY1.00",            "CHY1.00",        "1.00 CHY"}, // wrong ISO code
2586         // {"zh_CN",          "1234.56",  "CHY", "CHY1,234.56",        "CHY1,234.56",        "CHY1,234.56",        "CHY1,234.56",    "1,234.56 CHY"}, // wrong ISO code
2587         {"zh_CN",             "1",        "CNY", "\\u00A51.00",        "\\u00A51.00",        "\\u00A51.00",        "CNY\\u00A01.00",        "1.00\\u00A0\\u4EBA\\u6C11\\u5E01"},
2588         {"zh_CN",             "1234.56",  "CNY", "\\u00A51,234.56",    "\\u00A51,234.56",    "\\u00A51,234.56",    "CNY\\u00A01,234.56",    "1,234.56\\u00A0\\u4EBA\\u6C11\\u5E01"},
2589         {"ru_RU",             "1",        "RUB", "1,00\\u00A0\\u20BD", "1,00\\u00A0\\u20BD", "1,00\\u00A0\\u20BD", "1,00\\u00A0RUB",        "1,00 \\u0440\\u043E\\u0441\\u0441\\u0438\\u0439\\u0441\\u043A\\u043E\\u0433\\u043E "
2590                                                                                                                                             "\\u0440\\u0443\\u0431\\u043B\\u044F"},
2591         {"ru_RU",             "2",        "RUB", "2,00\\u00A0\\u20BD", "2,00\\u00A0\\u20BD", "2,00\\u00A0\\u20BD", "2,00\\u00A0RUB",        "2,00 \\u0440\\u043E\\u0441\\u0441\\u0438\\u0439\\u0441\\u043A\\u043E\\u0433\\u043E "
2592                                                                                                                                             "\\u0440\\u0443\\u0431\\u043B\\u044F"},
2593         {"ru_RU",             "5",        "RUB", "5,00\\u00A0\\u20BD", "5,00\\u00A0\\u20BD", "5,00\\u00A0\\u20BD", "5,00\\u00A0RUB",        "5,00 \\u0440\\u043E\\u0441\\u0441\\u0438\\u0439\\u0441\\u043A\\u043E\\u0433\\u043E "
2594                                                                                                                                             "\\u0440\\u0443\\u0431\\u043B\\u044F"},
2595         // test locale without currency information
2596         {"root",              "-1.23",    "USD", "-US$\\u00A01.23",    "-US$\\u00A01.23",    "-US$\\u00A01.23",    "-USD\\u00A01.23", "-1.23 USD"},
2597         {"root@cf=account",   "-1.23",    "USD", "-US$\\u00A01.23",    "-US$\\u00A01.23",    "-US$\\u00A01.23",    "-USD\\u00A01.23", "-1.23 USD"},
2598         // test choice format
2599         {"es_AR",             "1",        "INR", "INR\\u00A01,00",     "INR\\u00A01,00",     "INR\\u00A01,00",     "INR\\u00A01,00",  "1,00 rupia india"},
2600     };
2601     static const UNumberFormatStyle currencyStyles[] = {
2602         UNUM_CURRENCY,
2603         UNUM_CURRENCY_STANDARD,
2604         UNUM_CURRENCY_ACCOUNTING,
2605         UNUM_CURRENCY_ISO,
2606         UNUM_CURRENCY_PLURAL
2607     };
2608 
2609     int32_t i, sIndex;
2610 
2611     for (i=0; i<UPRV_LENGTHOF(DATA); ++i) {
2612       const char* localeString = DATA[i][0];
2613       double numberToBeFormat = atof(DATA[i][1]);
2614       const char* currencyISOCode = DATA[i][2];
2615       for (sIndex = 0; sIndex < UPRV_LENGTHOF(currencyStyles); ++sIndex) {
2616         UNumberFormatStyle style = currencyStyles[sIndex];
2617         UErrorCode status = U_ZERO_ERROR;
2618         UChar currencyCode[4];
2619         UChar ubufResult[kUBufMax];
2620         UChar ubufExpected[kUBufMax];
2621         int32_t ulenRes;
2622 
2623         UNumberFormat* unumFmt = unum_open(style, NULL, 0, localeString, NULL, &status);
2624         if (U_FAILURE(status)) {
2625             log_data_err("FAIL: unum_open, locale %s, style %d - %s\n", localeString, (int)style, myErrorName(status));
2626             continue;
2627         }
2628         u_charsToUChars(currencyISOCode, currencyCode, 4);
2629         unum_setTextAttribute(unumFmt, UNUM_CURRENCY_CODE, currencyCode, 3, &status);
2630         if (U_FAILURE(status)) {
2631             log_err("FAIL: unum_setTextAttribute, locale %s, UNUM_CURRENCY_CODE %s\n", localeString, currencyISOCode);
2632         }
2633         ulenRes = unum_formatDouble(unumFmt, numberToBeFormat, ubufResult, kUBufMax, NULL, &status);
2634         if (U_FAILURE(status)) {
2635             log_err("FAIL: unum_formatDouble, locale %s, UNUM_CURRENCY_CODE %s - %s\n", localeString, currencyISOCode, myErrorName(status));
2636         } else {
2637             int32_t ulenExp = u_unescape(DATA[i][3 + sIndex], ubufExpected, kUBufMax);
2638             if (ulenRes != ulenExp || u_strncmp(ubufResult, ubufExpected, ulenExp) != 0) {
2639                 log_err("FAIL: unum_formatDouble, locale %s, UNUM_CURRENCY_CODE %s, expected %s, got something else\n",
2640                         localeString, currencyISOCode, DATA[i][3 + sIndex]);
2641             }
2642         }
2643         unum_close(unumFmt);
2644       }
2645     }
2646 }
2647 
2648 typedef struct {
2649     const char * locale;
2650     UNumberFormatStyle style;
2651     UDisplayContext context;
2652     const char * expectedResult;
2653 } TestContextItem;
2654 
2655 /* currently no locales have contextTransforms data for "symbol" type */
2656 static const TestContextItem tcItems[] = { /* results for 123.45 */
2657     { "sv", UNUM_SPELLOUT, UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE,    "ett\\u00ADhundra\\u00ADtjugo\\u00ADtre komma fyra fem" },
2658     { "sv", UNUM_SPELLOUT, UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE, "Ett\\u00ADhundra\\u00ADtjugo\\u00ADtre komma fyra fem" },
2659     { "sv", UNUM_SPELLOUT, UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU,       "ett\\u00ADhundra\\u00ADtjugo\\u00ADtre komma fyra fem" },
2660     { "sv", UNUM_SPELLOUT, UDISPCTX_CAPITALIZATION_FOR_STANDALONE,            "ett\\u00ADhundra\\u00ADtjugo\\u00ADtre komma fyra fem" },
2661     { "en", UNUM_SPELLOUT, UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE,    "one hundred twenty-three point four five" },
2662     { "en", UNUM_SPELLOUT, UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE, "One hundred twenty-three point four five" },
2663     { "en", UNUM_SPELLOUT, UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU,       "One hundred twenty-three point four five" },
2664     { "en", UNUM_SPELLOUT, UDISPCTX_CAPITALIZATION_FOR_STANDALONE,            "One hundred twenty-three point four five" },
2665     { NULL, (UNumberFormatStyle)0, (UDisplayContext)0, NULL }
2666 };
2667 
TestContext(void)2668 static void TestContext(void) {
2669     UErrorCode status = U_ZERO_ERROR;
2670     const TestContextItem* itemPtr;
2671 
2672     UNumberFormat *unum = unum_open(UNUM_SPELLOUT, NULL, 0, "en", NULL, &status);
2673     if ( U_SUCCESS(status) ) {
2674         UDisplayContext context = unum_getContext(unum, UDISPCTX_TYPE_CAPITALIZATION, &status);
2675         if ( U_FAILURE(status) || context != UDISPCTX_CAPITALIZATION_NONE) {
2676             log_err("FAIL: Initial unum_getContext is not UDISPCTX_CAPITALIZATION_NONE\n");
2677             status = U_ZERO_ERROR;
2678         }
2679         unum_setContext(unum, UDISPCTX_CAPITALIZATION_FOR_STANDALONE, &status);
2680         context = unum_getContext(unum, UDISPCTX_TYPE_CAPITALIZATION, &status);
2681         if ( U_FAILURE(status) || context != UDISPCTX_CAPITALIZATION_FOR_STANDALONE) {
2682             log_err("FAIL: unum_getContext does not return the value set, UDISPCTX_CAPITALIZATION_FOR_STANDALONE\n");
2683         }
2684         unum_close(unum);
2685     } else {
2686         log_data_err("unum_open UNUM_SPELLOUT for en fails with status %s\n", myErrorName(status));
2687     }
2688 #if !UCONFIG_NO_NORMALIZATION && !UCONFIG_NO_BREAK_ITERATION
2689     for (itemPtr = tcItems; itemPtr->locale != NULL; itemPtr++) {
2690         UChar ubufResult[kUBufMax];
2691         int32_t ulenRes;
2692 
2693         status = U_ZERO_ERROR;
2694         unum = unum_open(itemPtr->style, NULL, 0, itemPtr->locale, NULL, &status);
2695         if (U_FAILURE(status)) {
2696             log_data_err("FAIL: unum_open, locale %s, style %d - %s\n",
2697                         itemPtr->locale, (int)itemPtr->style, myErrorName(status));
2698             continue;
2699         }
2700         unum_setContext(unum, itemPtr->context, &status);
2701         ulenRes = unum_formatDouble(unum, 123.45, ubufResult, kUBufMax, NULL, &status);
2702         if (U_FAILURE(status)) {
2703             log_err("FAIL: unum_formatDouble, locale %s, style %d, context %d - %s\n",
2704                     itemPtr->locale, (int)itemPtr->style, (int)itemPtr->context, myErrorName(status));
2705         } else {
2706             UChar ubufExpected[kUBufMax];
2707             int32_t ulenExp = u_unescape(itemPtr->expectedResult, ubufExpected, kUBufMax);
2708             if (ulenRes != ulenExp || u_strncmp(ubufResult, ubufExpected, ulenExp) != 0) {
2709                 char bbuf[kUBufMax*2];
2710                 u_austrncpy(bbuf, ubufResult, sizeof(bbuf));
2711                 log_err("FAIL: unum_formatDouble, locale %s, style %d, context %d, expected %d:\"%s\", got %d:\"%s\"\n",
2712                         itemPtr->locale, (int)itemPtr->style, (int)itemPtr->context, ulenExp,
2713                         itemPtr->expectedResult, ulenRes, bbuf);
2714             }
2715         }
2716         unum_close(unum);
2717     }
2718 #endif /* #if !UCONFIG_NO_NORMALIZATION && !UCONFIG_NO_BREAK_ITERATION */
2719 }
2720 
TestCurrencyUsage(void)2721 static void TestCurrencyUsage(void) {
2722     static const char* DATA[][2] = {
2723         /* the data are:
2724          * currency ISO code to be formatted,
2725          * format result using CURRENCYSTYLE with CASH purpose,-
2726          * Note that as of CLDR 26:-
2727          * - TWD switches from 0 decimals to 2; PKR still has 0, so change test to that
2728          * - CAD rounds to .05
2729          */
2730 
2731         {"PKR", "PKR\\u00A0124"},
2732         {"CAD", "CA$123.55"},
2733         {"USD", "$123.57"}
2734     };
2735 
2736     // 1st time for getter/setter, 2nd for factory method
2737     int32_t i;
2738     for(i=0; i<2; i++){
2739         const char* localeString = "en_US";
2740         double numberToBeFormat = 123.567;
2741         UNumberFormat* unumFmt;
2742         UNumberFormatStyle style = UNUM_CURRENCY;
2743         UErrorCode status = U_ZERO_ERROR;
2744         int32_t j;
2745 
2746         if(i == 1){ // change for factory method
2747             style = UNUM_CASH_CURRENCY;
2748         }
2749 
2750         unumFmt = unum_open(style, NULL, 0, localeString, NULL, &status);
2751         if (U_FAILURE(status)) {
2752             log_data_err("FAIL: unum_open, locale %s, style %d - %s\n",
2753                         localeString, (int)style, myErrorName(status));
2754             continue;
2755         }
2756 
2757         if(i == 0){ // this is for the getter/setter
2758             if(unum_getAttribute(unumFmt, UNUM_CURRENCY_USAGE) != UCURR_USAGE_STANDARD) {
2759                 log_err("FAIL: currency usage attribute is not UNUM_CURRENCY_STANDARD\n");
2760             }
2761 
2762             unum_setAttribute(unumFmt, UNUM_CURRENCY_USAGE, UCURR_USAGE_CASH);
2763         }
2764 
2765         if(unum_getAttribute(unumFmt, UNUM_CURRENCY_USAGE) != UCURR_USAGE_CASH) {
2766             log_err("FAIL: currency usage attribute is not UNUM_CASH_CURRENCY\n");
2767         }
2768 
2769         for (j=0; j<UPRV_LENGTHOF(DATA); ++j) {
2770             UChar expect[64];
2771             int32_t expectLen;
2772             UChar currencyCode[4];
2773             UChar result[64];
2774             int32_t resultLen;
2775             UFieldPosition pos = {0};
2776 
2777             u_charsToUChars(DATA[j][0], currencyCode, 3);
2778             expectLen = u_unescape(DATA[j][1], expect, UPRV_LENGTHOF(expect));
2779 
2780             unum_setTextAttribute(unumFmt, UNUM_CURRENCY_CODE, currencyCode, 3, &status);
2781             assertSuccess("num_setTextAttribute()", &status);
2782 
2783             resultLen = unum_formatDouble(unumFmt, numberToBeFormat, result, UPRV_LENGTHOF(result),
2784                                         &pos, &status);
2785             assertSuccess("num_formatDouble()", &status);
2786 
2787             if(resultLen != expectLen || u_strcmp(result, expect) != 0) {
2788                 log_err("Fail: Error in Number Format Currency Purpose using unum_setAttribute() expected: %s, got %s\n",
2789                 aescstrdup(expect, expectLen), aescstrdup(result, resultLen));
2790             }
2791 
2792         }
2793 
2794         unum_close(unumFmt);
2795     }
2796 }
2797 
2798 static UChar currFmtNegSameAsPos[] = /* "\u00A4#,##0.00;\u00A4#,##0.00" */
2799     {0xA4,0x23,0x2C,0x23,0x23,0x30,0x2E,0x30,0x30,0x3B,0xA4,0x23,0x2C,0x23,0x23,0x30,0x2E,0x30,0x30,0};
2800 
2801 // NOTE: As of ICU 62, identical positive and negative subpatterns means no minus sign!
2802 // See CLDR ticket https://unicode.org/cldr/trac/ticket/10703
2803 //static UChar currFmtToPatExpected[] = /* "\u00A4#,##0.00" */
2804 //    {0xA4,0x23,0x2C,0x23,0x23,0x30,0x2E,0x30,0x30,0};
2805 static const UChar* currFmtToPatExpected = currFmtNegSameAsPos;
2806 
2807 static UChar currFmtResultExpected[] = /* "$100.00" */
2808     {0x24,0x31,0x30,0x30,0x2E,0x30,0x30,0};
2809 
2810 static UChar emptyString[] = {0};
2811 
2812 enum { kUBufSize = 64, kBBufSize = 128 };
2813 
TestCurrFmtNegSameAsPositive(void)2814 static void TestCurrFmtNegSameAsPositive(void) {
2815     UErrorCode status = U_ZERO_ERROR;
2816     UNumberFormat* unumfmt = unum_open(UNUM_CURRENCY, NULL, 0, "en_US", NULL, &status);
2817     if ( U_SUCCESS(status) ) {
2818         unum_applyPattern(unumfmt, false, currFmtNegSameAsPos, -1, NULL, &status);
2819         if (U_SUCCESS(status)) {
2820             UChar ubuf[kUBufSize];
2821             int32_t ulen = unum_toPattern(unumfmt, false, ubuf, kUBufSize, &status);
2822             if (U_FAILURE(status)) {
2823                 log_err("unum_toPattern fails with status %s\n", myErrorName(status));
2824             } else if (u_strcmp(ubuf, currFmtToPatExpected) != 0) {
2825                 log_err("unum_toPattern result wrong, expected %s, got %s\n", aescstrdup(currFmtToPatExpected,-1), aescstrdup(ubuf,ulen));
2826             }
2827             unum_setSymbol(unumfmt, UNUM_MINUS_SIGN_SYMBOL, emptyString, 0, &status);
2828             if (U_SUCCESS(status)) {
2829                 ulen = unum_formatDouble(unumfmt, -100.0, ubuf, kUBufSize, NULL, &status);
2830                 if (U_FAILURE(status)) {
2831                     log_err("unum_formatDouble fails with status %s\n", myErrorName(status));
2832                 } else if (u_strcmp(ubuf, currFmtResultExpected) != 0) {
2833                     log_err("unum_formatDouble result wrong, expected %s, got %s\n", aescstrdup(currFmtResultExpected,-1), aescstrdup(ubuf,ulen));
2834                 }
2835             } else {
2836                 log_err("unum_setSymbol fails with status %s\n", myErrorName(status));
2837             }
2838         } else {
2839             log_err("unum_applyPattern fails with status %s\n", myErrorName(status));
2840         }
2841         unum_close(unumfmt);
2842     } else {
2843         log_data_err("unum_open UNUM_CURRENCY for en_US fails with status %s\n", myErrorName(status));
2844     }
2845 }
2846 
2847 
2848 typedef struct {
2849   double value;
2850   const char *expected;
2851 } ValueAndExpectedString;
2852 
2853 static const ValueAndExpectedString enShort[] = {
2854   {0.0, "0"},
2855   {0.17, "0.17"},
2856   {1.0, "1"},
2857   {1234.0, "1.2K"},
2858   {12345.0, "12K"},
2859   {123456.0, "123K"},
2860   {1234567.0, "1.2M"},
2861   {12345678.0, "12M"},
2862   {123456789.0, "123M"},
2863   {1.23456789E9, "1.2B"},
2864   {1.23456789E10, "12B"},
2865   {1.23456789E11, "123B"},
2866   {1.23456789E12, "1.2T"},
2867   {1.23456789E13, "12T"},
2868   {1.23456789E14, "123T"},
2869   {1.23456789E15, "1235T"},
2870   {0.0, NULL}
2871 };
2872 
2873 static const ValueAndExpectedString enShortMax2[] = {
2874   {0.0, "0"},
2875   {0.17, "0.17"},
2876   {1.0, "1"},
2877   {1234.0, "1.2K"},
2878   {12345.0, "12K"},
2879   {123456.0, "120K"},
2880   {1234567.0, "1.2M"},
2881   {12345678.0, "12M"},
2882   {123456789.0, "120M"},
2883   {1.23456789E9, "1.2B"},
2884   {1.23456789E10, "12B"},
2885   {1.23456789E11, "120B"},
2886   {1.23456789E12, "1.2T"},
2887   {1.23456789E13, "12T"},
2888   {1.23456789E14, "120T"},
2889   {1.23456789E15, "1200T"},
2890   {0.0, NULL}
2891 };
2892 
2893 static const ValueAndExpectedString enShortMax5[] = {
2894   {0.0, "0"},
2895   {0.17, "0.17"},
2896   {1.0, "1"},
2897   {1234.0, "1.234K"},
2898   {12345.0, "12.345K"},
2899   {123456.0, "123.46K"},
2900   {1234567.0, "1.2346M"},
2901   {12345678.0, "12.346M"},
2902   {123456789.0, "123.46M"},
2903   {1.23456789E9, "1.2346B"},
2904   {1.23456789E10, "12.346B"},
2905   {1.23456789E11, "123.46B"},
2906   {1.23456789E12, "1.2346T"},
2907   {1.23456789E13, "12.346T"},
2908   {1.23456789E14, "123.46T"},
2909   {1.23456789E15, "1234.6T"},
2910   {0.0, NULL}
2911 };
2912 
2913 static const ValueAndExpectedString enShortMin3[] = {
2914   {0.0, "0.00"},
2915   {0.17, "0.170"},
2916   {1.0, "1.00"},
2917   {1234.0, "1.23K"},
2918   {12345.0, "12.3K"},
2919   {123456.0, "123K"},
2920   {1234567.0, "1.23M"},
2921   {12345678.0, "12.3M"},
2922   {123456789.0, "123M"},
2923   {1.23456789E9, "1.23B"},
2924   {1.23456789E10, "12.3B"},
2925   {1.23456789E11, "123B"},
2926   {1.23456789E12, "1.23T"},
2927   {1.23456789E13, "12.3T"},
2928   {1.23456789E14, "123T"},
2929   {1.23456789E15, "1230T"},
2930   {0.0, NULL}
2931 };
2932 
2933 static const ValueAndExpectedString jaShortMax2[] = {
2934   {1234.0, "1200"},
2935   {12345.0, "1.2\\u4E07"},
2936   {123456.0, "12\\u4E07"},
2937   {1234567.0, "120\\u4E07"},
2938   {12345678.0, "1200\\u4E07"},
2939   {123456789.0, "1.2\\u5104"},
2940   {1.23456789E9, "12\\u5104"},
2941   {1.23456789E10, "120\\u5104"},
2942   {1.23456789E11, "1200\\u5104"},
2943   {1.23456789E12, "1.2\\u5146"},
2944   {1.23456789E13, "12\\u5146"},
2945   {1.23456789E14, "120\\u5146"},
2946   {0.0, NULL}
2947 };
2948 
2949 static const ValueAndExpectedString srLongMax2[] = {
2950   {1234.0, "1,2 \\u0445\\u0438\\u0459\\u0430\\u0434\\u0435"}, // 10^3 few
2951   {12345.0, "12 \\u0445\\u0438\\u0459\\u0430\\u0434\\u0430"}, // 10^3 other
2952   {21789.0, "22 \\u0445\\u0438\\u0459\\u0430\\u0434\\u0435"}, // 10^3 few
2953   {123456.0, "120 \\u0445\\u0438\\u0459\\u0430\\u0434\\u0430"}, // 10^3 other
2954   {999999.0, "1 \\u043C\\u0438\\u043B\\u0438\\u043E\\u043D"}, // 10^6 one
2955   {1234567.0, "1,2 \\u043C\\u0438\\u043B\\u0438\\u043E\\u043D\\u0430"}, // 10^6 few
2956   {12345678.0, "12 \\u043C\\u0438\\u043B\\u0438\\u043E\\u043D\\u0430"}, // 10^6 other
2957   {123456789.0, "120 \\u043C\\u0438\\u043B\\u0438\\u043E\\u043D\\u0430"}, // 10^6 other
2958   {1.23456789E9, "1,2 \\u043C\\u0438\\u043B\\u0438\\u0458\\u0430\\u0440\\u0434\\u0435"}, // 10^9 few
2959   {1.23456789E10, "12 \\u043C\\u0438\\u043B\\u0438\\u0458\\u0430\\u0440\\u0434\\u0438"}, // 10^9 other
2960   {2.08901234E10, "21 \\u043C\\u0438\\u043B\\u0438\\u0458\\u0430\\u0440\\u0434\\u0430"}, // 10^9 one
2961   {2.18901234E10, "22 \\u043C\\u0438\\u043B\\u0438\\u0458\\u0430\\u0440\\u0434\\u0435"}, // 10^9 few
2962   {1.23456789E11, "120 \\u043C\\u0438\\u043B\\u0438\\u0458\\u0430\\u0440\\u0434\\u0438"}, // 10^9 other
2963   {-1234.0, "-1,2 \\u0445\\u0438\\u0459\\u0430\\u0434\\u0435"},
2964   {-12345.0, "-12 \\u0445\\u0438\\u0459\\u0430\\u0434\\u0430"},
2965   {-21789.0, "-22 \\u0445\\u0438\\u0459\\u0430\\u0434\\u0435"},
2966   {-123456.0, "-120 \\u0445\\u0438\\u0459\\u0430\\u0434\\u0430"},
2967   {-999999.0, "-1 \\u043C\\u0438\\u043B\\u0438\\u043E\\u043D"},
2968   {-1234567.0, "-1,2 \\u043C\\u0438\\u043B\\u0438\\u043E\\u043D\\u0430"},
2969   {-12345678.0, "-12 \\u043C\\u0438\\u043B\\u0438\\u043E\\u043D\\u0430"},
2970   {-123456789.0, "-120 \\u043C\\u0438\\u043B\\u0438\\u043E\\u043D\\u0430"},
2971   {-1.23456789E9, "-1,2 \\u043C\\u0438\\u043B\\u0438\\u0458\\u0430\\u0440\\u0434\\u0435"},
2972   {-1.23456789E10, "-12 \\u043C\\u0438\\u043B\\u0438\\u0458\\u0430\\u0440\\u0434\\u0438"},
2973   {-2.08901234E10, "-21 \\u043C\\u0438\\u043B\\u0438\\u0458\\u0430\\u0440\\u0434\\u0430"},
2974   {-2.18901234E10, "-22 \\u043C\\u0438\\u043B\\u0438\\u0458\\u0430\\u0440\\u0434\\u0435"},
2975   {-1.23456789E11, "-120 \\u043C\\u0438\\u043B\\u0438\\u0458\\u0430\\u0440\\u0434\\u0438"},
2976   {0.0, NULL}
2977 };
2978 
2979 typedef struct {
2980     const char *       locale;
2981     UNumberFormatStyle style;
2982     int32_t            attribute; // UNumberFormatAttribute, or -1 for none
2983     int32_t            attrValue; //
2984     const ValueAndExpectedString * veItems;
2985 } LocStyleAttributeTest;
2986 
2987 static const LocStyleAttributeTest lsaTests[] = {
2988   { "en",   UNUM_DECIMAL_COMPACT_SHORT,     -1,                             0,  enShort },
2989   { "en",   UNUM_DECIMAL_COMPACT_SHORT,     UNUM_MAX_SIGNIFICANT_DIGITS,    2,  enShortMax2 },
2990   { "en",   UNUM_DECIMAL_COMPACT_SHORT,     UNUM_MAX_SIGNIFICANT_DIGITS,    5,  enShortMax5 },
2991   { "en",   UNUM_DECIMAL_COMPACT_SHORT,     UNUM_MIN_SIGNIFICANT_DIGITS,    3,  enShortMin3 },
2992   { "ja",   UNUM_DECIMAL_COMPACT_SHORT,     UNUM_MAX_SIGNIFICANT_DIGITS,    2,  jaShortMax2 },
2993   { "sr",   UNUM_DECIMAL_COMPACT_LONG,      UNUM_MAX_SIGNIFICANT_DIGITS,    2,  srLongMax2  },
2994   { NULL,   (UNumberFormatStyle)0,          -1,                             0,  NULL }
2995 };
2996 
TestVariousStylesAndAttributes(void)2997 static void TestVariousStylesAndAttributes(void) {
2998     const LocStyleAttributeTest * lsaTestPtr;
2999     for (lsaTestPtr = lsaTests; lsaTestPtr->locale != NULL; lsaTestPtr++) {
3000         UErrorCode status = U_ZERO_ERROR;
3001         UNumberFormat * unum = unum_open(lsaTestPtr->style, NULL, 0, lsaTestPtr->locale, NULL, &status);
3002         if ( U_FAILURE(status) ) {
3003             log_data_err("FAIL: unum_open style %d, locale %s: error %s\n", (int)lsaTestPtr->style, lsaTestPtr->locale, u_errorName(status));
3004         } else {
3005             const ValueAndExpectedString * veItemPtr;
3006             if (lsaTestPtr->attribute >= 0) {
3007                 unum_setAttribute(unum, (UNumberFormatAttribute)lsaTestPtr->attribute, lsaTestPtr->attrValue);
3008             }
3009             // ICU 62: should call minSignificantDigits in tandem with maxSignificantDigits.
3010             if (lsaTestPtr->attribute == UNUM_MIN_SIGNIFICANT_DIGITS) {
3011                 unum_setAttribute(unum, UNUM_MAX_SIGNIFICANT_DIGITS, lsaTestPtr->attrValue);
3012             }
3013             for (veItemPtr = lsaTestPtr->veItems; veItemPtr->expected != NULL; veItemPtr++) {
3014                 UChar uexp[kUBufSize];
3015                 UChar uget[kUBufSize];
3016                 int32_t uexplen, ugetlen;
3017 
3018                 status = U_ZERO_ERROR;
3019                 uexplen = u_unescape(veItemPtr->expected, uexp, kUBufSize);
3020                 ugetlen = unum_formatDouble(unum, veItemPtr->value, uget, kUBufSize, NULL, &status);
3021                 if ( U_FAILURE(status) ) {
3022                     log_err("FAIL: unum_formatDouble style %d, locale %s, attr %d, value %.2f: error %s\n",
3023                             (int)lsaTestPtr->style, lsaTestPtr->locale, lsaTestPtr->attribute, veItemPtr->value, u_errorName(status));
3024                 } else if (ugetlen != uexplen || u_strncmp(uget, uexp, uexplen) != 0) {
3025                     char bexp[kBBufSize];
3026                     char bget[kBBufSize];
3027                     u_strToUTF8(bexp, kBBufSize, NULL, uexp, uexplen, &status);
3028                     u_strToUTF8(bget, kBBufSize, NULL, uget, ugetlen, &status);
3029                     log_err("FAIL: unum_formatDouble style %d, locale %s, attr %d, value %.2f: expect \"%s\", get \"%s\"\n",
3030                             (int)lsaTestPtr->style, lsaTestPtr->locale, lsaTestPtr->attribute, veItemPtr->value, bexp, bget);
3031                 }
3032             }
3033             unum_close(unum);
3034         }
3035     }
3036 }
3037 
3038 static const UChar currpat[]  = { 0xA4,0x23,0x2C,0x23,0x23,0x30,0x2E,0x30,0x30,0};
3039 static const UChar parsetxt[] = { 0x78,0x30,0x79,0x24,0 }; /* x0y$ */
3040 
TestParseCurrPatternWithDecStyle()3041 static void TestParseCurrPatternWithDecStyle() {
3042     UErrorCode status = U_ZERO_ERROR;
3043     UNumberFormat *unumfmt = unum_open(UNUM_DECIMAL, NULL, 0, "en_US", NULL, &status);
3044     if (U_FAILURE(status)) {
3045         log_data_err("unum_open DECIMAL failed for en_US: %s (Are you missing data?)\n", u_errorName(status));
3046     } else {
3047         unum_applyPattern(unumfmt, false, currpat, -1, NULL, &status);
3048         if (U_FAILURE(status)) {
3049             log_err_status(status, "unum_applyPattern failed: %s\n", u_errorName(status));
3050         } else {
3051             int32_t pos = 0;
3052             double value = unum_parseDouble(unumfmt, parsetxt, -1, &pos, &status);
3053             if (U_SUCCESS(status)) {
3054                 log_err_status(status, "unum_parseDouble expected to fail but got status %s, value %f\n", u_errorName(status), value);
3055             }
3056         }
3057         unum_close(unumfmt);
3058     }
3059 }
3060 
3061 /*
3062  * Ticket #12684
3063  * Test unum_formatDoubleForFields (and UFieldPositionIterator)
3064  */
3065 
3066 typedef struct {
3067     int32_t field;
3068     int32_t beginPos;
3069     int32_t endPos;
3070 } FieldsData;
3071 
3072 typedef struct {
3073     const char *       locale;
3074     UNumberFormatStyle style;
3075     double             value;
3076     const FieldsData * expectedFields;
3077 } FormatForFieldsItem;
3078 
3079 static const UChar patNoFields[] = { 0x0027, 0x0078, 0x0027, 0 }; /* "'x'", for UNUM_PATTERN_DECIMAL */
3080 
3081 
3082 /* "en_US", UNUM_CURRENCY, 123456.0 : "¤#,##0.00" => "$123,456.00" */
3083 static const FieldsData fields_en_CURR[] = {
3084     { UNUM_CURRENCY_FIELD /*7*/,            0, 1 },
3085     { UNUM_GROUPING_SEPARATOR_FIELD /*6*/,  4, 5 },
3086     { UNUM_INTEGER_FIELD /*0*/,             1, 8 },
3087     { UNUM_DECIMAL_SEPARATOR_FIELD /*2*/,   8, 9 },
3088     { UNUM_FRACTION_FIELD /*1*/,            9, 11 },
3089     { -1, -1, -1 },
3090 };
3091 /* "en_US", UNUM_PERCENT, -34 : "#,##0%" => "-34%" */
3092 static const FieldsData fields_en_PRCT[] = {
3093     { UNUM_SIGN_FIELD /*10*/,               0, 1 },
3094     { UNUM_INTEGER_FIELD /*0*/,             1, 3 },
3095     { UNUM_PERCENT_FIELD /*8*/,             3, 4 },
3096     { -1, -1, -1 },
3097 };
3098 /* "fr_FR", UNUM_CURRENCY, 123456.0 : "#,##0.00 ¤" => "123,456.00 €" */
3099 static const FieldsData fields_fr_CURR[] = {
3100     { UNUM_GROUPING_SEPARATOR_FIELD /*6*/,  3, 4 },
3101     { UNUM_INTEGER_FIELD /*0*/,             0, 7 },
3102     { UNUM_DECIMAL_SEPARATOR_FIELD /*2*/,   7, 8 },
3103     { UNUM_FRACTION_FIELD /*1*/,            8, 10 },
3104     { UNUM_CURRENCY_FIELD /*7*/,           11, 12 },
3105     { -1, -1, -1 },
3106 };
3107 /* "en_US", UNUM_PATTERN_DECIMAL, 12.0 : "'x'" => "x12" */
3108 static const FieldsData fields_en_PATN[] = {
3109     { UNUM_INTEGER_FIELD /*0*/,             1, 3 },
3110     { -1, -1, -1 },
3111 };
3112 
3113 static const FormatForFieldsItem fffItems[] = {
3114     { "en_US", UNUM_CURRENCY_STANDARD, 123456.0, fields_en_CURR },
3115     { "en_US", UNUM_PERCENT,              -0.34, fields_en_PRCT },
3116     { "fr_FR", UNUM_CURRENCY_STANDARD, 123456.0, fields_fr_CURR },
3117     { "en_US", UNUM_PATTERN_DECIMAL,       12.0, fields_en_PATN },
3118     { NULL, (UNumberFormatStyle)0, 0, NULL },
3119 };
3120 
TestFormatForFields(void)3121 static void TestFormatForFields(void) {
3122     UErrorCode status = U_ZERO_ERROR;
3123     UFieldPositionIterator* fpositer = ufieldpositer_open(&status);
3124     if ( U_FAILURE(status) ) {
3125         log_err("ufieldpositer_open fails, status %s\n", u_errorName(status));
3126     } else {
3127         const FormatForFieldsItem * itemPtr;
3128         for (itemPtr = fffItems; itemPtr->locale != NULL; itemPtr++) {
3129             UNumberFormat* unum;
3130             status = U_ZERO_ERROR;
3131             unum = (itemPtr->style == UNUM_PATTERN_DECIMAL)?
3132                 unum_open(itemPtr->style, patNoFields, -1, itemPtr->locale, NULL, &status):
3133                 unum_open(itemPtr->style, NULL, 0, itemPtr->locale, NULL, &status);
3134             if ( U_FAILURE(status) ) {
3135                 log_data_err("unum_open fails for locale %s, style %d: status %s (Are you missing data?)\n", itemPtr->locale, itemPtr->style, u_errorName(status));
3136             } else {
3137                 UChar ubuf[kUBufSize];
3138                 int32_t ulen = unum_formatDoubleForFields(unum, itemPtr->value, ubuf, kUBufSize, fpositer, &status);
3139                 if ( U_FAILURE(status) ) {
3140                     log_err("unum_formatDoubleForFields fails for locale %s, style %d: status %s\n", itemPtr->locale, itemPtr->style, u_errorName(status));
3141                 } else {
3142                     const FieldsData * fptr;
3143                     int32_t field, beginPos, endPos;
3144                     for (fptr = itemPtr->expectedFields; true; fptr++) {
3145                         field = ufieldpositer_next(fpositer, &beginPos, &endPos);
3146                         if (field != fptr->field || (field >= 0 && (beginPos != fptr->beginPos || endPos != fptr->endPos))) {
3147                             if (fptr->field >= 0) {
3148                                 log_err("unum_formatDoubleForFields for locale %s as \"%s\"; expect field %d range %d-%d, get field %d range %d-%d\n",
3149                                     itemPtr->locale, aescstrdup(ubuf, ulen), fptr->field, fptr->beginPos, fptr->endPos, field, beginPos, endPos);
3150                             } else {
3151                                 log_err("unum_formatDoubleForFields for locale %s as \"%s\"; expect field < 0, get field %d range %d-%d\n",
3152                                     itemPtr->locale, aescstrdup(ubuf, ulen), field, beginPos, endPos);
3153                             }
3154                             break;
3155                         }
3156                         if (field < 0) {
3157                             break;
3158                         }
3159                     }
3160                 }
3161                 unum_close(unum);
3162             }
3163         }
3164         ufieldpositer_close(fpositer);
3165     }
3166 }
3167 
Test12052_NullPointer()3168 static void Test12052_NullPointer() {
3169     UErrorCode status = U_ZERO_ERROR;
3170     static const UChar input[] = u"199a";
3171     UChar currency[200] = {0};
3172     UNumberFormat *theFormatter = unum_open(UNUM_CURRENCY, NULL, 0, "en_US", NULL, &status);
3173     if (!assertSuccessCheck("unum_open() failed", &status, true)) { return; }
3174     status = U_ZERO_ERROR;
3175     unum_setAttribute(theFormatter, UNUM_LENIENT_PARSE, 1);
3176     int32_t pos = 1;
3177     unum_parseDoubleCurrency(theFormatter, input, -1, &pos, currency, &status);
3178     assertEquals("should fail gracefully", "U_PARSE_ERROR", u_errorName(status));
3179     unum_close(theFormatter);
3180 }
3181 
3182 typedef struct {
3183     const char*  locale;
3184     const UChar* text;       // text to parse
3185     UBool        lenient;    // leniency to use
3186     UBool        intOnly;    // whether to set PARSE_INT_ONLY
3187     UErrorCode   intStatus;  // expected status from parse
3188     int32_t      intPos;     // expected final pos from parse
3189     int32_t      intValue;   // expected value from parse
3190     UErrorCode   doubStatus; // expected status from parseDouble
3191     int32_t      doubPos;    // expected final pos from parseDouble
3192     double       doubValue;  // expected value from parseDouble
3193     UErrorCode   decStatus;  // expected status from parseDecimal
3194     int32_t      decPos;     // expected final pos from parseDecimal
3195     const char*  decString;  // expected output string from parseDecimal
3196 
3197 } ParseCaseItem;
3198 
3199 static const ParseCaseItem parseCaseItems[] = {
3200     { "en", u"0,000",            false, false, U_ZERO_ERROR,            5,          0, U_ZERO_ERROR,  5,                0.0, U_ZERO_ERROR,  5, "0" },
3201     { "en", u"0,000",            true,  false, U_ZERO_ERROR,            5,          0, U_ZERO_ERROR,  5,                0.0, U_ZERO_ERROR,  5, "0" },
3202     { "en", u"1000,000",         false, false, U_PARSE_ERROR,           0,          0, U_PARSE_ERROR, 0,                0.0, U_PARSE_ERROR, 0, "" },
3203     { "en", u"1000,000",         true,  false, U_ZERO_ERROR,            8,    1000000, U_ZERO_ERROR,  8,          1000000.0, U_ZERO_ERROR,  8, "1000000" },
3204     { "en", u"",                 false, false, U_PARSE_ERROR,           0,          0, U_PARSE_ERROR, 0,                0.0, U_PARSE_ERROR, 0, "" },
3205     { "en", u"",                 true,  false, U_PARSE_ERROR,           0,          0, U_PARSE_ERROR, 0,                0.0, U_PARSE_ERROR, 0, "" },
3206     { "en", u"9999990000503021", false, false, U_INVALID_FORMAT_ERROR, 16, 2147483647, U_ZERO_ERROR, 16, 9999990000503020.0, U_ZERO_ERROR, 16, "9999990000503021" },
3207     { "en", u"9999990000503021", false, true,  U_INVALID_FORMAT_ERROR, 16, 2147483647, U_ZERO_ERROR, 16, 9999990000503020.0, U_ZERO_ERROR, 16, "9999990000503021" },
3208     { "en", u"1000000.5",        false, false, U_ZERO_ERROR,            9,    1000000, U_ZERO_ERROR,  9,          1000000.5, U_ZERO_ERROR,  9, "1.0000005E+6"},
3209     { "en", u"1000000.5",        false, true,  U_ZERO_ERROR,            7,    1000000, U_ZERO_ERROR,  7,          1000000.0, U_ZERO_ERROR,  7, "1000000" },
3210     { "en", u"123.5",            false, false, U_ZERO_ERROR,            5,        123, U_ZERO_ERROR,  5,              123.5, U_ZERO_ERROR,  5, "123.5" },
3211     { "en", u"123.5",            false, true,  U_ZERO_ERROR,            3,        123, U_ZERO_ERROR,  3,              123.0, U_ZERO_ERROR,  3, "123" },
3212     { NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0.0, 0, 0, NULL }
3213 };
3214 
TestParseCases(void)3215 static void TestParseCases(void) {
3216     const ParseCaseItem* itemPtr;
3217     for (itemPtr = parseCaseItems; itemPtr->locale != NULL; itemPtr++) {
3218         UErrorCode status = U_ZERO_ERROR;
3219         UNumberFormat* unumDec = unum_open(UNUM_DECIMAL, NULL, 0, itemPtr->locale, NULL, &status);
3220         if (U_FAILURE(status)) {
3221             log_data_err("unum_open UNUM_DECIMAL fails for locale %s: %s\n", itemPtr->locale, u_errorName(status));
3222             continue;
3223         }
3224         int32_t intValue, parsePos, dclen;
3225         double doubValue;
3226         char decstr[32];
3227         unum_setAttribute(unumDec, UNUM_LENIENT_PARSE, itemPtr->lenient);
3228         unum_setAttribute(unumDec, UNUM_PARSE_INT_ONLY, itemPtr->intOnly);
3229 
3230         parsePos = 0;
3231         status = U_ZERO_ERROR;
3232         intValue = unum_parse(unumDec, itemPtr->text, -1, &parsePos, &status);
3233         if (status != itemPtr->intStatus || parsePos != itemPtr->intPos || intValue != itemPtr->intValue) {
3234             char btext[32];
3235             u_austrcpy(btext, itemPtr->text);
3236             log_err("locale %s, text \"%s\", lenient %d, intOnly %d;\n      parse        expected status %s, pos %d, value %d;\n                   got   %s, %d, %d\n",
3237                     itemPtr->locale, btext, itemPtr->lenient, itemPtr->intOnly,
3238                     u_errorName(itemPtr->intStatus), itemPtr->intPos, itemPtr->intValue,
3239                     u_errorName(status), parsePos, intValue);
3240         }
3241 
3242         parsePos = 0;
3243         status = U_ZERO_ERROR;
3244         doubValue = unum_parseDouble(unumDec, itemPtr->text, -1, &parsePos, &status);
3245         if (status != itemPtr->doubStatus || parsePos != itemPtr->doubPos || doubValue != itemPtr->doubValue) {
3246             char btext[32];
3247             u_austrcpy(btext, itemPtr->text);
3248             log_err("locale %s, text \"%s\", lenient %d, intOnly %d;\n      parseDouble  expected status %s, pos %d, value %.1f;\n                   got   %s, %d, %.1f\n",
3249                     itemPtr->locale, btext, itemPtr->lenient, itemPtr->intOnly,
3250                     u_errorName(itemPtr->doubStatus), itemPtr->doubPos, itemPtr->doubValue,
3251                     u_errorName(status), parsePos, doubValue);
3252         }
3253 
3254         parsePos = 0;
3255         status = U_ZERO_ERROR;
3256         decstr[0] = 0;
3257         dclen = unum_parseDecimal(unumDec, itemPtr->text, -1, &parsePos, decstr, 32, &status);
3258         (void)dclen;
3259         if (status != itemPtr->decStatus || parsePos != itemPtr->decPos || uprv_strcmp(decstr,itemPtr->decString) != 0) {
3260             char btext[32];
3261             u_austrcpy(btext, itemPtr->text);
3262             log_err("locale %s, text \"%s\", lenient %d, intOnly %d;\n      parseDecimal expected status %s, pos %d, str \"%s\";\n                   got   %s, %d, \"%s\"\n",
3263                     itemPtr->locale, btext, itemPtr->lenient, itemPtr->intOnly,
3264                     u_errorName(itemPtr->decStatus), itemPtr->decPos, itemPtr->decString,
3265                     u_errorName(status), parsePos, decstr);
3266         }
3267 
3268         unum_close(unumDec);
3269     }
3270 }
3271 
3272 typedef struct {
3273     const char*        descrip;
3274     const char*        locale;
3275     UNumberFormatStyle style;
3276     int32_t            minInt;
3277     int32_t            minFrac;
3278     int32_t            maxFrac;
3279     double             roundIncr;
3280     const UChar*       expPattern;
3281     double             valueToFmt;
3282     const UChar*       expFormat;
3283 } SetMaxFracAndRoundIncrItem;
3284 
3285 static const SetMaxFracAndRoundIncrItem maxFracAndRoundIncrItems[] = {
3286     // descrip                     locale   style         mnI mnF mxF rdInc   expPat         value  expFmt
3287     { "01 en_US DEC 1/0/3/0.0",    "en_US", UNUM_DECIMAL,  1,  0,  3, 0.0,    u"#,##0.###",  0.128, u"0.128" },
3288     { "02 en_US DEC 1/0/1/0.0",    "en_US", UNUM_DECIMAL,  1,  0,  1, 0.0,    u"#,##0.#",    0.128, u"0.1"   },
3289     { "03 en_US DEC 1/0/1/0.01",   "en_US", UNUM_DECIMAL,  1,  0,  1, 0.01,   u"#,##0.#",    0.128, u"0.1"   },
3290     { "04 en_US DEC 1/1/1/0.01",   "en_US", UNUM_DECIMAL,  1,  1,  1, 0.01,   u"#,##0.0",    0.128, u"0.1"   },
3291     { "05 en_US DEC 1/0/1/0.1",    "en_US", UNUM_DECIMAL,  1,  0,  1, 0.1,    u"#,##0.1",    0.128, u"0.1"   }, // use incr
3292     { "06 en_US DEC 1/1/1/0.1",    "en_US", UNUM_DECIMAL,  1,  1,  1, 0.1,    u"#,##0.1",    0.128, u"0.1"   }, // use incr
3293 
3294     { "10 en_US DEC 1/0/1/0.02",   "en_US", UNUM_DECIMAL,  1,  0,  1, 0.02,   u"#,##0.#",    0.128, u"0.1"   },
3295     { "11 en_US DEC 1/0/2/0.02",   "en_US", UNUM_DECIMAL,  1,  0,  2, 0.02,   u"#,##0.02",   0.128, u"0.12"  }, // use incr
3296     { "12 en_US DEC 1/0/3/0.02",   "en_US", UNUM_DECIMAL,  1,  0,  3, 0.02,   u"#,##0.02#",  0.128, u"0.12"  }, // use incr
3297     { "13 en_US DEC 1/1/1/0.02",   "en_US", UNUM_DECIMAL,  1,  1,  1, 0.02,   u"#,##0.0",    0.128, u"0.1"   },
3298     { "14 en_US DEC 1/1/2/0.02",   "en_US", UNUM_DECIMAL,  1,  1,  2, 0.02,   u"#,##0.02",   0.128, u"0.12"  }, // use incr
3299     { "15 en_US DEC 1/1/3/0.02",   "en_US", UNUM_DECIMAL,  1,  1,  3, 0.02,   u"#,##0.02#",  0.128, u"0.12"  }, // use incr
3300     { "16 en_US DEC 1/2/2/0.02",   "en_US", UNUM_DECIMAL,  1,  2,  2, 0.02,   u"#,##0.02",   0.128, u"0.12"  }, // use incr
3301     { "17 en_US DEC 1/2/3/0.02",   "en_US", UNUM_DECIMAL,  1,  2,  3, 0.02,   u"#,##0.02#",  0.128, u"0.12"  }, // use incr
3302     { "18 en_US DEC 1/3/3/0.02",   "en_US", UNUM_DECIMAL,  1,  3,  3, 0.02,   u"#,##0.020",  0.128, u"0.120" }, // use incr
3303 
3304     { "20 en_US DEC 1/1/1/0.0075", "en_US", UNUM_DECIMAL,  1,  1,  1, 0.0075, u"#,##0.0",    0.019, u"0.0"    },
3305     { "21 en_US DEC 1/1/2/0.0075", "en_US", UNUM_DECIMAL,  1,  1,  2, 0.0075, u"#,##0.0075", 0.004, u"0.0075" }, // use incr
3306     { "22 en_US DEC 1/1/2/0.0075", "en_US", UNUM_DECIMAL,  1,  1,  2, 0.0075, u"#,##0.0075", 0.019, u"0.0225" }, // use incr
3307     { "23 en_US DEC 1/1/3/0.0075", "en_US", UNUM_DECIMAL,  1,  1,  3, 0.0075, u"#,##0.0075", 0.004, u"0.0075" }, // use incr
3308     { "24 en_US DEC 1/1/3/0.0075", "en_US", UNUM_DECIMAL,  1,  1,  3, 0.0075, u"#,##0.0075", 0.019, u"0.0225" }, // use incr
3309     { "25 en_US DEC 1/2/2/0.0075", "en_US", UNUM_DECIMAL,  1,  2,  2, 0.0075, u"#,##0.0075", 0.004, u"0.0075" }, // use incr
3310     { "26 en_US DEC 1/2/2/0.0075", "en_US", UNUM_DECIMAL,  1,  2,  2, 0.0075, u"#,##0.0075", 0.019, u"0.0225" }, // use incr
3311     { "27 en_US DEC 1/2/3/0.0075", "en_US", UNUM_DECIMAL,  1,  2,  3, 0.0075, u"#,##0.0075", 0.004, u"0.0075" }, // use incr
3312     { "28 en_US DEC 1/2/3/0.0075", "en_US", UNUM_DECIMAL,  1,  2,  3, 0.0075, u"#,##0.0075", 0.019, u"0.0225" }, // use incr
3313     { "29 en_US DEC 1/3/3/0.0075", "en_US", UNUM_DECIMAL,  1,  3,  3, 0.0075, u"#,##0.0075", 0.004, u"0.0075" }, // use incr
3314     { "2A en_US DEC 1/3/3/0.0075", "en_US", UNUM_DECIMAL,  1,  3,  3, 0.0075, u"#,##0.0075", 0.019, u"0.0225" }, // use incr
3315 
3316     { NULL, NULL, UNUM_IGNORE, 0, 0, 0, 0.0, NULL, 0.0, NULL }
3317 };
3318 
3319 // The following is copied from C++ number_patternstring.cpp for this C test.
3320 //
3321 // Determine whether a given roundingIncrement should be ignored for formatting
3322 // based on the current maxFrac value (maximum fraction digits). For example a
3323 // roundingIncrement of 0.01 should be ignored if maxFrac is 1, but not if maxFrac
3324 // is 2 or more. Note that roundingIncrements are rounded in significance, so
3325 // a roundingIncrement of 0.006 is treated like 0.01 for this determination, i.e.
3326 // it should not be ignored if maxFrac is 2 or more (but a roundingIncrement of
3327 // 0.005 is treated like 0.001 for significance). This is the reason for the
3328 // initial doubling below.
3329 // roundIncr must be non-zero
ignoreRoundingIncrement(double roundIncr,int32_t maxFrac)3330 static UBool ignoreRoundingIncrement(double roundIncr, int32_t maxFrac) {
3331     if (maxFrac < 0) {
3332         return false;
3333     }
3334     int32_t frac = 0;
3335     roundIncr *= 2.0;
3336     for (frac = 0; frac <= maxFrac && roundIncr <= 1.0; frac++, roundIncr *= 10.0);
3337     return (frac > maxFrac);
3338 }
3339 
3340 enum { kBBufMax = 128 };
TestSetMaxFracAndRoundIncr(void)3341 static void TestSetMaxFracAndRoundIncr(void) {
3342     const SetMaxFracAndRoundIncrItem* itemPtr;
3343     for (itemPtr = maxFracAndRoundIncrItems; itemPtr->descrip != NULL; itemPtr++) {
3344         UChar ubuf[kUBufMax];
3345         char  bbufe[kBBufMax];
3346         char  bbufg[kBBufMax];
3347         int32_t ulen;
3348         UErrorCode status = U_ZERO_ERROR;
3349         UNumberFormat* unf = unum_open(itemPtr->style, NULL, 0, itemPtr->locale, NULL, &status);
3350         if (U_FAILURE(status)) {
3351             log_data_err("locale %s: unum_open style %d fails with %s\n", itemPtr->locale, itemPtr->style, u_errorName(status));
3352             continue;
3353         }
3354 
3355         unum_setAttribute(unf, UNUM_MIN_INTEGER_DIGITS, itemPtr->minInt);
3356         unum_setAttribute(unf, UNUM_MIN_FRACTION_DIGITS, itemPtr->minFrac);
3357         unum_setAttribute(unf, UNUM_MAX_FRACTION_DIGITS, itemPtr->maxFrac);
3358         unum_setDoubleAttribute(unf, UNUM_ROUNDING_INCREMENT, itemPtr->roundIncr);
3359 
3360         UBool roundIncrUsed = (itemPtr->roundIncr != 0.0 && !ignoreRoundingIncrement(itemPtr->roundIncr, itemPtr->maxFrac));
3361 
3362         int32_t minInt = unum_getAttribute(unf, UNUM_MIN_INTEGER_DIGITS);
3363         if (minInt != itemPtr->minInt) {
3364             log_err("test %s: unum_getAttribute UNUM_MIN_INTEGER_DIGITS, expected %d, got %d\n",
3365                     itemPtr->descrip, itemPtr->minInt, minInt);
3366         }
3367         int32_t minFrac = unum_getAttribute(unf, UNUM_MIN_FRACTION_DIGITS);
3368         if (minFrac != itemPtr->minFrac) {
3369             log_err("test %s: unum_getAttribute UNUM_MIN_FRACTION_DIGITS, expected %d, got %d\n",
3370                     itemPtr->descrip, itemPtr->minFrac, minFrac);
3371         }
3372         // If incrementRounding is used, maxFrac is set equal to minFrac
3373         int32_t maxFrac = unum_getAttribute(unf, UNUM_MAX_FRACTION_DIGITS);
3374         // If incrementRounding is used, maxFrac is set equal to minFrac
3375         int32_t expMaxFrac = (roundIncrUsed)? itemPtr->minFrac: itemPtr->maxFrac;
3376         if (maxFrac != expMaxFrac) {
3377             log_err("test %s: unum_getAttribute UNUM_MAX_FRACTION_DIGITS, expected %d, got %d\n",
3378                     itemPtr->descrip, expMaxFrac, maxFrac);
3379         }
3380         double roundIncr = unum_getDoubleAttribute(unf, UNUM_ROUNDING_INCREMENT);
3381         // If incrementRounding is not used, roundIncr is set to 0.0
3382         double expRoundIncr = (roundIncrUsed)? itemPtr->roundIncr: 0.0;
3383         if (roundIncr != expRoundIncr) {
3384             log_err("test %s: unum_getDoubleAttribute UNUM_ROUNDING_INCREMENT, expected %f, got %f\n",
3385                     itemPtr->descrip, expRoundIncr, roundIncr);
3386         }
3387 
3388         status = U_ZERO_ERROR;
3389         ulen = unum_toPattern(unf, false, ubuf, kUBufMax, &status);
3390         (void)ulen;
3391         if ( U_FAILURE(status) ) {
3392             log_err("test %s: unum_toPattern fails with %s\n", itemPtr->descrip, u_errorName(status));
3393         } else if (u_strcmp(ubuf,itemPtr->expPattern)!=0) {
3394             u_austrcpy(bbufe, itemPtr->expPattern);
3395             u_austrcpy(bbufg, ubuf);
3396             log_err("test %s: unum_toPattern expect \"%s\", get \"%s\"\n", itemPtr->descrip, bbufe, bbufg);
3397         }
3398 
3399         status = U_ZERO_ERROR;
3400         ulen = unum_formatDouble(unf, itemPtr->valueToFmt, ubuf, kUBufMax, NULL, &status);
3401         if ( U_FAILURE(status) ) {
3402             log_err("test %s: unum_formatDouble fails with %s\n", itemPtr->descrip, u_errorName(status));
3403         } else if (u_strcmp(ubuf,itemPtr->expFormat)!=0) {
3404             u_austrcpy(bbufe, itemPtr->expFormat);
3405             u_austrcpy(bbufg, ubuf);
3406             log_err("test %s: unum_formatDouble expect \"%s\", get \"%s\"\n", itemPtr->descrip, bbufe, bbufg);
3407         }
3408 
3409         unum_close(unf);
3410     }
3411 }
3412 
TestIgnorePadding(void)3413 static void TestIgnorePadding(void) {
3414     UErrorCode status = U_ZERO_ERROR;
3415     UNumberFormat* unum = unum_open(UNUM_PATTERN_DECIMAL, NULL, 0, "en_US", NULL, &status);
3416     if (U_FAILURE(status)) {
3417         log_data_err("unum_open UNUM_PATTERN_DECIMAL for en_US and NULL pattern fails:%s\n", u_errorName(status));
3418     } else {
3419         unum_setAttribute(unum, UNUM_GROUPING_USED, 0);
3420         unum_setAttribute(unum, UNUM_FORMAT_WIDTH, 0);
3421         unum_setTextAttribute(unum, UNUM_PADDING_CHARACTER, u"*", 1, &status);
3422         if (U_FAILURE(status)) {
3423             log_err("unum_setTextAttribute UNUM_PADDING_CHARACTER to '*' fails: %s\n", u_errorName(status));
3424         } else {
3425             unum_setAttribute(unum, UNUM_PADDING_POSITION, 0);
3426             unum_setAttribute(unum, UNUM_MIN_INTEGER_DIGITS, 0);
3427             unum_setAttribute(unum, UNUM_MAX_INTEGER_DIGITS, 8);
3428             unum_setAttribute(unum, UNUM_MIN_FRACTION_DIGITS, 0);
3429             unum_setAttribute(unum, UNUM_MAX_FRACTION_DIGITS, 0);
3430 
3431             UChar ubuf[kUBufMax];
3432             int32_t ulen = unum_toPattern(unum, false, ubuf, kUBufMax, &status);
3433             if (U_FAILURE(status)) {
3434                 log_err("unum_toPattern fails: %s\n", u_errorName(status));
3435             } else {
3436                 char bbuf[kBBufMax];
3437                 if (ulen > 0 && ubuf[0]==u'*') {
3438                     ubuf[kUBufMax-1] = 0; // ensure zero termination
3439                     u_austrncpy(bbuf, ubuf, kBBufMax);
3440                     log_err("unum_toPattern result should ignore padding but get %s\n", bbuf);
3441                 }
3442                 unum_applyPattern(unum, false, ubuf, ulen, NULL, &status);
3443                 if (U_FAILURE(status)) {
3444                     log_err("unum_applyPattern fails: %s\n", u_errorName(status));
3445                 } else {
3446                     ulen = unum_formatDecimal(unum, "24", -1, ubuf, kUBufMax, NULL, &status);
3447                     if (U_FAILURE(status)) {
3448                         log_err("unum_formatDecimal fails: %s\n", u_errorName(status));
3449                     } else if (u_strcmp(ubuf, u"24") != 0) {
3450                         ubuf[kUBufMax-1] = 0; // ensure zero termination
3451                         u_austrncpy(bbuf, ubuf, kBBufMax);
3452                         log_err("unum_formatDecimal result expect 24 but get %s\n", bbuf);
3453                     }
3454                 }
3455             }
3456         }
3457         unum_close(unum);
3458     }
3459 }
3460 
TestSciNotationMaxFracCap(void)3461 static void TestSciNotationMaxFracCap(void) {
3462     static const UChar* pat1 = u"#.##E+00;-#.##E+00";
3463     UErrorCode status = U_ZERO_ERROR;
3464     UNumberFormat* unum = unum_open(UNUM_PATTERN_DECIMAL, pat1, -1, "en_US", NULL, &status);
3465     if ( U_FAILURE(status) ) {
3466         log_data_err("unum_open UNUM_PATTERN_DECIMAL with scientific pattern for \"en_US\" fails with %s\n", u_errorName(status));
3467     } else {
3468         double value;
3469         UChar ubuf[kUBufMax];
3470         char bbuf[kBBufMax];
3471         int32_t ulen;
3472 
3473         unum_setAttribute(unum, UNUM_MIN_FRACTION_DIGITS, 0);
3474         unum_setAttribute(unum, UNUM_MAX_FRACTION_DIGITS, 2147483647);
3475         ulen = unum_toPattern(unum, false, ubuf, kUBufMax, &status);
3476         if ( U_SUCCESS(status) ) {
3477             u_austrncpy(bbuf, ubuf, kUBufMax);
3478             log_info("unum_toPattern (%d): %s\n", ulen, bbuf);
3479         }
3480 
3481         for (value = 10.0; value < 1000000000.0; value *= 10.0) {
3482             status = U_ZERO_ERROR;
3483             ulen = unum_formatDouble(unum, value, ubuf, kUBufMax, NULL, &status);
3484             if ( U_FAILURE(status) ) {
3485                 log_err("unum_formatDouble value %.1f status %s\n", value, u_errorName(status));
3486             } else if (u_strncmp(ubuf,u"1E+0",4) != 0) {
3487                 u_austrncpy(bbuf, ubuf, kUBufMax);
3488                 log_err("unum_formatDouble value %.1f expected result to begin with 1E+0, got %s\n", value, bbuf);
3489             }
3490         }
3491         unum_close(unum);
3492     }
3493 }
3494 
TestMinIntMinFracZero(void)3495 static void TestMinIntMinFracZero(void) {
3496     UErrorCode status = U_ZERO_ERROR;
3497     UNumberFormat* unum = unum_open(UNUM_DECIMAL, NULL, 0, "en_US", NULL, &status);
3498     if ( U_FAILURE(status) ) {
3499         log_data_err("unum_open UNUM_DECIMAL for en_US fails with %s\n", u_errorName(status));
3500     } else {
3501         UChar ubuf[kUBufMax];
3502         char  bbuf[kBBufMax];
3503         int minInt, minFrac, ulen;
3504 
3505         unum_setAttribute(unum, UNUM_MIN_INTEGER_DIGITS, 0);
3506         unum_setAttribute(unum, UNUM_MIN_FRACTION_DIGITS, 0);
3507         minInt = unum_getAttribute(unum, UNUM_MIN_INTEGER_DIGITS);
3508         minFrac = unum_getAttribute(unum, UNUM_MIN_FRACTION_DIGITS);
3509         if (minInt != 0 || minFrac != 0) {
3510             log_err("after setting minInt=minFrac=0, get minInt %d, minFrac %d\n", minInt, minFrac);
3511         }
3512 
3513         ulen = unum_toPattern(unum, false, ubuf, kUBufMax, &status);
3514         if ( U_FAILURE(status) ) {
3515             log_err("unum_toPattern fails with %s\n", u_errorName(status));
3516         } else if (ulen < 3 || u_strstr(ubuf, u"#.#")==NULL) {
3517             u_austrncpy(bbuf, ubuf, kUBufMax);
3518             log_info("after setting minInt=minFrac=0, expect pattern to contain \"#.#\", but get (%d): \"%s\"\n", ulen, bbuf);
3519         }
3520 
3521         status = U_ZERO_ERROR;
3522         ulen = unum_formatDouble(unum, 10.0, ubuf, kUBufMax, NULL, &status);
3523         if ( U_FAILURE(status) ) {
3524             log_err("unum_formatDouble 10.0 ulen %d fails with %s\n", ulen, u_errorName(status));
3525         } else if (u_strcmp(ubuf, u"10") != 0) {
3526             u_austrncpy(bbuf, ubuf, kUBufMax);
3527             log_err("unum_formatDouble 10.0 expected \"10\", got \"%s\"\n", bbuf);
3528         }
3529 
3530         status = U_ZERO_ERROR;
3531         ulen = unum_formatDouble(unum, 0.9, ubuf, kUBufMax, NULL, &status);
3532         if ( U_FAILURE(status) ) {
3533             log_err("unum_formatDouble 0.9 ulen %d fails with %s\n", ulen, u_errorName(status));
3534         } else if (u_strcmp(ubuf, u".9") != 0) {
3535             u_austrncpy(bbuf, ubuf, kUBufMax);
3536             log_err("unum_formatDouble 0.9 expected \".9\", got \"%s\"\n", bbuf);
3537         }
3538 
3539         status = U_ZERO_ERROR;
3540         ulen = unum_formatDouble(unum, 0.0, ubuf, kUBufMax, NULL, &status);
3541         if ( U_FAILURE(status) ) {
3542             log_err("unum_formatDouble 0.0 ulen %d fails with %s\n", ulen, u_errorName(status));
3543         } else if (u_strcmp(ubuf, u"0") != 0) {
3544             u_austrncpy(bbuf, ubuf, kUBufMax);
3545             log_err("unum_formatDouble 0.0 expected \"0\", got \"%s\"\n", bbuf);
3546         }
3547 
3548         unum_close(unum);
3549         status = U_ZERO_ERROR;
3550         unum = unum_open(UNUM_CURRENCY, NULL, 0, "en_US", NULL, &status);
3551         if ( U_FAILURE(status) ) {
3552             log_data_err("unum_open UNUM_CURRENCY for en_US fails with %s\n", u_errorName(status));
3553         } else {
3554             unum_setAttribute(unum, UNUM_MIN_INTEGER_DIGITS, 0);
3555             unum_setAttribute(unum, UNUM_MIN_FRACTION_DIGITS, 0);
3556             minInt = unum_getAttribute(unum, UNUM_MIN_INTEGER_DIGITS);
3557             minFrac = unum_getAttribute(unum, UNUM_MIN_FRACTION_DIGITS);
3558             if (minInt != 0 || minFrac != 0) {
3559                 log_err("after setting CURRENCY minInt=minFrac=0, get minInt %d, minFrac %d\n", minInt, minFrac);
3560             }
3561 
3562             status = U_ZERO_ERROR;
3563             ulen = unum_formatDouble(unum, 10.0, ubuf, kUBufMax, NULL, &status);
3564             if ( U_FAILURE(status) ) {
3565                 log_err("unum_formatDouble (CURRENCY) 10.0 ulen %d fails with %s\n", ulen, u_errorName(status));
3566             } else if (u_strcmp(ubuf, u"$10") != 0) {
3567                 u_austrncpy(bbuf, ubuf, kUBufMax);
3568                 log_err("unum_formatDouble (CURRENCY) 10.0 expected \"$10\", got \"%s\"\n", bbuf);
3569             }
3570 
3571             status = U_ZERO_ERROR;
3572             ulen = unum_formatDouble(unum, 0.9, ubuf, kUBufMax, NULL, &status);
3573             if ( U_FAILURE(status) ) {
3574                 log_err("unum_formatDouble (CURRENCY) 0.9 ulen %d fails with %s\n", ulen, u_errorName(status));
3575             } else if (u_strcmp(ubuf, u"$.9") != 0) {
3576                 u_austrncpy(bbuf, ubuf, kUBufMax);
3577                 log_err("unum_formatDouble (CURRENCY) 0.9 expected \"$.9\", got \"%s\"\n", bbuf);
3578             }
3579 
3580             status = U_ZERO_ERROR;
3581             ulen = unum_formatDouble(unum, 0.0, ubuf, kUBufMax, NULL, &status);
3582             if ( U_FAILURE(status) ) {
3583                 log_err("unum_formatDouble (CURRENCY) 0.0 ulen %d fails with %s\n", ulen, u_errorName(status));
3584             } else if (u_strcmp(ubuf, u"$0") != 0) {
3585                 u_austrncpy(bbuf, ubuf, kUBufMax);
3586                 log_err("unum_formatDouble (CURRENCY) 0.0 expected \"$0\", got \"%s\"\n", bbuf);
3587             }
3588 
3589             unum_close(unum);
3590         }
3591     }
3592 }
3593 
Test21479_ExactCurrency(void)3594 static void Test21479_ExactCurrency(void) {
3595     UErrorCode status = U_ZERO_ERROR;
3596     UNumberFormat* nf = unum_open(UNUM_CURRENCY, NULL, 0, "en_US", NULL, &status);
3597     if ( U_FAILURE(status) ) {
3598         log_data_err("unum_open UNUM_CURRENCY for en_US fails with %s\n", u_errorName(status));
3599         goto cleanup;
3600     }
3601     unum_setTextAttribute(nf, UNUM_CURRENCY_CODE, u"EUR", -1, &status);
3602     UChar result[40];
3603     unum_formatDecimal(nf, "987654321000000000000001", -1, result, 40, NULL, &status);
3604     if (!assertSuccess("Formatting currency decimal", &status)) {
3605         goto cleanup;
3606     }
3607     assertUEquals("", u"€987,654,321,000,000,000,000,001.00", result);
3608 
3609     cleanup:
3610     unum_close(nf);
3611 }
3612 
Test22088_Ethiopic(void)3613 static void Test22088_Ethiopic(void) {
3614     UErrorCode err = U_ZERO_ERROR;
3615     UNumberFormat* nf1 = unum_open(UNUM_DEFAULT, NULL, 0, "am_ET@numbers=ethi", NULL, &err);
3616     UNumberFormat* nf2 = unum_open(UNUM_NUMBERING_SYSTEM, NULL, 0, "am_ET@numbers=ethi", NULL, &err);
3617     UNumberFormat* nf3 = unum_open(UNUM_NUMBERING_SYSTEM, NULL, 0, "en_US", NULL, &err);
3618 
3619     if (assertSuccess("Creation of number formatters failed", &err)) {
3620         UChar result[200];
3621 
3622         unum_formatDouble(nf1, 123, result, 200, NULL, &err);
3623         assertSuccess("Formatting of number failed", &err);
3624         assertUEquals("Wrong result with UNUM_DEFAULT", u"፻፳፫", result);
3625 
3626         unum_formatDouble(nf2, 123, result, 200, NULL, &err);
3627         assertSuccess("Formatting of number failed", &err);
3628         assertUEquals("Wrong result with UNUM_NUMBERING_SYSTEM", u"፻፳፫", result);
3629 
3630         unum_formatDouble(nf3, 123, result, 200, NULL, &err);
3631         assertSuccess("Formatting of number failed", &err);
3632         assertUEquals("Wrong result with UNUM_NUMBERING_SYSTEM and English", u"123", result);
3633     }
3634     unum_close(nf1);
3635     unum_close(nf2);
3636     unum_close(nf3);
3637 }
3638 
TestParseWithEmptyCurr(void)3639 static void TestParseWithEmptyCurr(void) {
3640     UErrorCode status = U_ZERO_ERROR;
3641     UNumberFormat* unum = unum_open(UNUM_CURRENCY, NULL, 0, "en_US", NULL, &status);
3642     if (U_FAILURE(status)) {
3643         log_data_err("unum_open UNUM_CURRENCY for \"en_US\" fails with %s\n", u_errorName(status));
3644     } else {
3645         unum_setSymbol(unum, UNUM_CURRENCY_SYMBOL, u"", 0, &status);
3646         if (U_FAILURE(status)) {
3647             log_err("unum_setSymbol UNUM_CURRENCY_SYMBOL u\"\" fails with %s\n", u_errorName(status));
3648         } else {
3649             char bbuf[kBBufMax] = { 0 };
3650             UChar curr[4] = { 0 };
3651             int32_t ppos, blen;
3652             double val;
3653             const UChar* text = u"3";
3654 
3655             status = U_ZERO_ERROR;
3656             ppos = 0;
3657             blen = unum_parseDecimal(unum, text, -1, &ppos, bbuf, kBBufMax, &status);
3658             if (U_FAILURE(status)) {
3659                 log_err("unum_parseDecimal u\"3\" with empty curr symbol fails with %s, ppos %d\n", u_errorName(status), ppos);
3660             } else if (ppos != 1 || blen != 1 || bbuf[0] != '3') {
3661                 log_err("unum_parseDecimal expect ppos 1, blen 1, str 3; get %d, %d, %s\n", ppos, blen, bbuf);
3662             }
3663 
3664             status = U_ZERO_ERROR;
3665             ppos = 0;
3666             val = unum_parseDouble(unum, text, -1, &ppos, &status);
3667             if (U_FAILURE(status)) {
3668                 log_err("unum_parseDouble u\"3\" with empty curr symbol fails with %s, ppos %d\n", u_errorName(status), ppos);
3669             } else if (ppos != 1 || val != 3.0) {
3670                 log_err("unum_parseDouble expect ppos 1, val 3.0; get %d, %.2f\n", ppos, val);
3671             }
3672 
3673             status = U_ZERO_ERROR;
3674             ppos = 0;
3675             val = unum_parseDoubleCurrency(unum, text, -1, &ppos, curr, &status);
3676             if (U_SUCCESS(status)) {
3677                 log_err("unum_parseDoubleCurrency u\"3\" with empty curr symbol succeeds, get ppos %d, val %.2f\n", ppos, val);
3678             }
3679         }
3680         unum_close(unum);
3681     }
3682 
3683     //                              "¤#,##0.00" "¤ #,##0.00" "#,##0.00 ¤" "#,##,##0.00¤"
3684     static const char* locales[] = {"en_US",    "nb_NO",     "cs_CZ",     "bn_BD",       NULL };
3685     const char ** localesPtr = locales;
3686     const char* locale;
3687     while ((locale = *localesPtr++) != NULL) {
3688         status = U_ZERO_ERROR;
3689         unum = unum_open(UNUM_CURRENCY, NULL, 0, locale, NULL, &status);
3690         if (U_FAILURE(status)) {
3691             log_data_err("locale %s unum_open UNUM_CURRENCY fails with %s\n", locale, u_errorName(status));
3692         } else {
3693             UChar ubuf[kUBufMax];
3694             int32_t ppos, ulen;
3695             const double posValToUse = 37.0;
3696             const double negValToUse = -3.0;
3697             double val;
3698 
3699             status = U_ZERO_ERROR;
3700             unum_setSymbol(unum, UNUM_CURRENCY_SYMBOL, u"", 0, &status);
3701             if (U_FAILURE(status)) {
3702                 log_err("locale %s unum_setSymbol UNUM_CURRENCY_SYMBOL u\"\" fails with %s, skipping\n", locale, u_errorName(status));
3703                 continue;
3704             }
3705 
3706             status = U_ZERO_ERROR;
3707             ulen = unum_formatDouble(unum, posValToUse, ubuf, kUBufMax, NULL, &status);
3708             if (U_FAILURE(status)) {
3709                 log_err("locale %s unum_formatDouble %.1f fails with %s, skipping\n", locale, posValToUse, u_errorName(status));
3710                 continue;
3711             }
3712 
3713             status = U_ZERO_ERROR;
3714             ppos = 0;
3715             val = unum_parseDouble(unum, ubuf, ulen, &ppos, &status);
3716             if (U_FAILURE(status)) {
3717                 log_err("locale %s unum_parseDouble fails with %s, ppos %d, expect %.1f\n", locale, u_errorName(status), ppos, posValToUse);
3718             } else if (ppos != ulen || val != posValToUse) {
3719                 log_err("locale %s unum_parseDouble expect ppos %d, val %.1f; get %d, %.2f\n", locale, ulen, posValToUse, ppos, val);
3720             }
3721 
3722             status = U_ZERO_ERROR;
3723             ulen = unum_formatDouble(unum, negValToUse, ubuf, kUBufMax, NULL, &status);
3724             if (U_FAILURE(status)) {
3725                 log_err("locale %s unum_formatDouble %.1f fails with %s, skipping\n", locale, negValToUse, u_errorName(status));
3726                 continue;
3727             }
3728 
3729             status = U_ZERO_ERROR;
3730             ppos = 0;
3731             val = unum_parseDouble(unum, ubuf, ulen, &ppos, &status);
3732             if (U_FAILURE(status)) {
3733                 log_err("locale %s unum_parseDouble fails with %s, ppos %d, expect %.1f\n", locale, u_errorName(status), ppos, negValToUse);
3734             } else if (ppos != ulen || val != negValToUse) {
3735                 log_err("locale %s unum_parseDouble expect ppos %d, val %.1f; get %d, %.2f\n", locale, ulen, negValToUse, ppos, val);
3736             }
3737 
3738             status = U_ZERO_ERROR;
3739             unum_applyPattern(unum, false, u"#,##0.00¤", -1, NULL, &status);
3740             if (U_FAILURE(status)) {
3741                 log_err("locale %s unum_applyPattern \"#,##0.00¤\" fails with %s, skipping\n", locale, u_errorName(status));
3742                 continue;
3743             }
3744 
3745             status = U_ZERO_ERROR;
3746             ulen = unum_formatDouble(unum, posValToUse, ubuf, kUBufMax, NULL, &status);
3747             if (U_FAILURE(status)) {
3748                 log_err("locale %s with \"#,##0.00¤\" unum_formatDouble %.1f fails with %s, skipping\n", locale, posValToUse, u_errorName(status));
3749                 continue;
3750             }
3751 
3752             status = U_ZERO_ERROR;
3753             ppos = 0;
3754             val = unum_parseDouble(unum, ubuf, ulen, &ppos, &status);
3755             if (U_FAILURE(status)) {
3756                 log_err("locale %s with \"#,##0.00¤\" unum_parseDouble fails with %s, ppos %d, expect %.1f\n", locale, u_errorName(status), ppos, posValToUse);
3757             } else if (ppos != ulen || val != posValToUse) {
3758                 log_err("locale %s with \"#,##0.00¤\" unum_parseDouble expect ppos %d, val %.1f; get %d, %.2f\n", locale, ulen, posValToUse, ppos, val);
3759             }
3760 
3761             status = U_ZERO_ERROR;
3762             ulen = unum_formatDouble(unum, negValToUse, ubuf, kUBufMax, NULL, &status);
3763             if (U_FAILURE(status)) {
3764                 log_err("locale %s with \"#,##0.00¤\" unum_formatDouble %.1f fails with %s, skipping\n", locale, negValToUse, u_errorName(status));
3765                 continue;
3766             }
3767 
3768             status = U_ZERO_ERROR;
3769             ppos = 0;
3770             val = unum_parseDouble(unum, ubuf, ulen, &ppos, &status);
3771             if (U_FAILURE(status)) {
3772                 log_err("locale %s with \"#,##0.00¤\" unum_parseDouble fails with %s, ppos %d, expect %.1f\n", locale, u_errorName(status), ppos, negValToUse);
3773             } else if (ppos != ulen || val != negValToUse) {
3774                 log_err("locale %s with \"#,##0.00¤\" unum_parseDouble expect ppos %d, val %.1f; get %d, %.2f\n", locale, ulen, negValToUse, ppos, val);
3775             }
3776 
3777             unum_close(unum);
3778         }
3779     }
3780 }
3781 
3782 #endif /* #if !UCONFIG_NO_FORMATTING */
3783