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