kernel32: Reimplement GetCurrencyFormatA().
[wine.git] / dlls / kernel32 / lcformat.c
blobde31db5c113ca4f8de48519cfdc087cd07f2701d
1 /*
2 * Locale-dependent format handling
4 * Copyright 1995 Martin von Loewis
5 * Copyright 1998 David Lee Lambert
6 * Copyright 2000 Julio César Gázquez
7 * Copyright 2003 Jon Griffiths
8 * Copyright 2005 Dmitry Timoshkov
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 #include <string.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <stdlib.h>
30 #include "windef.h"
31 #include "winbase.h"
32 #include "winnls.h"
33 #include "wine/debug.h"
34 #include "winternl.h"
36 #include "kernel_private.h"
38 WINE_DEFAULT_DEBUG_CHANNEL(nls);
40 #define DATE_DATEVARSONLY 0x0100 /* only date stuff: yMdg */
41 #define TIME_TIMEVARSONLY 0x0200 /* only time stuff: hHmst */
43 /* Since calculating the formatting data for each locale is time-consuming,
44 * we get the format data for each locale only once and cache it in memory.
45 * We cache both the system default and user overridden data, after converting
46 * them into the formats that the functions here expect. Since these functions
47 * will typically be called with only a small number of the total locales
48 * installed, the memory overhead is minimal while the speedup is significant.
50 * Our cache takes the form of a singly linked list, whose node is below:
52 #define NLS_NUM_CACHED_STRINGS 57
54 typedef struct _NLS_FORMAT_NODE
56 LCID lcid; /* Locale Id */
57 DWORD dwFlags; /* 0 or LOCALE_NOUSEROVERRIDE */
58 DWORD dwCodePage; /* Default code page (if LOCALE_USE_ANSI_CP not given) */
59 NUMBERFMTW fmt; /* Default format for numbers */
60 CURRENCYFMTW cyfmt; /* Default format for currencies */
61 LPWSTR lppszStrings[NLS_NUM_CACHED_STRINGS]; /* Default formats,day/month names */
62 WCHAR szShortAM[2]; /* Short 'AM' marker */
63 WCHAR szShortPM[2]; /* Short 'PM' marker */
64 struct _NLS_FORMAT_NODE *next;
65 } NLS_FORMAT_NODE;
67 /* Macros to get particular data strings from a format node */
68 #define GetNegative(fmt) fmt->lppszStrings[0]
69 #define GetLongDate(fmt) fmt->lppszStrings[1]
70 #define GetShortDate(fmt) fmt->lppszStrings[2]
71 #define GetTime(fmt) fmt->lppszStrings[3]
72 #define GetAM(fmt) fmt->lppszStrings[54]
73 #define GetPM(fmt) fmt->lppszStrings[55]
74 #define GetYearMonth(fmt) fmt->lppszStrings[56]
76 #define GetLongDay(fmt,day) fmt->lppszStrings[4 + day]
77 #define GetShortDay(fmt,day) fmt->lppszStrings[11 + day]
78 #define GetLongMonth(fmt,mth) fmt->lppszStrings[18 + mth]
79 #define GetGenitiveMonth(fmt,mth) fmt->lppszStrings[30 + mth]
80 #define GetShortMonth(fmt,mth) fmt->lppszStrings[42 + mth]
82 /* Write access to the cache is protected by this critical section */
83 static CRITICAL_SECTION NLS_FormatsCS;
84 static CRITICAL_SECTION_DEBUG NLS_FormatsCS_debug =
86 0, 0, &NLS_FormatsCS,
87 { &NLS_FormatsCS_debug.ProcessLocksList,
88 &NLS_FormatsCS_debug.ProcessLocksList },
89 0, 0, { (DWORD_PTR)(__FILE__ ": NLS_Formats") }
91 static CRITICAL_SECTION NLS_FormatsCS = { &NLS_FormatsCS_debug, -1, 0, 0, 0, 0 };
93 /**************************************************************************
94 * NLS_GetLocaleNumber <internal>
96 * Get a numeric locale format value.
98 static DWORD NLS_GetLocaleNumber(LCID lcid, DWORD dwFlags)
100 WCHAR szBuff[80];
101 DWORD dwVal = 0;
103 szBuff[0] = '\0';
104 GetLocaleInfoW(lcid, dwFlags, szBuff, ARRAY_SIZE(szBuff));
106 if (szBuff[0] && szBuff[1] == ';' && szBuff[2] != '0')
107 dwVal = (szBuff[0] - '0') * 10 + (szBuff[2] - '0');
108 else
110 const WCHAR* iter = szBuff;
111 dwVal = 0;
112 while(*iter >= '0' && *iter <= '9')
113 dwVal = dwVal * 10 + (*iter++ - '0');
115 return dwVal;
118 /**************************************************************************
119 * NLS_GetLocaleString <internal>
121 * Get a string locale format value.
123 static WCHAR* NLS_GetLocaleString(LCID lcid, DWORD dwFlags)
125 WCHAR szBuff[80], *str;
126 DWORD dwLen;
128 szBuff[0] = '\0';
129 GetLocaleInfoW(lcid, dwFlags, szBuff, ARRAY_SIZE(szBuff));
130 dwLen = lstrlenW(szBuff) + 1;
131 str = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
132 if (str)
133 memcpy(str, szBuff, dwLen * sizeof(WCHAR));
134 return str;
137 #define GET_LOCALE_NUMBER(num, type) num = NLS_GetLocaleNumber(lcid, type|dwFlags); \
138 TRACE( #type ": %ld (%08lx)\n", (DWORD)num, (DWORD)num)
140 #define GET_LOCALE_STRING(str, type) str = NLS_GetLocaleString(lcid, type|dwFlags); \
141 TRACE( #type ": %s\n", debugstr_w(str))
143 /**************************************************************************
144 * NLS_GetFormats <internal>
146 * Calculate (and cache) the number formats for a locale.
148 static const NLS_FORMAT_NODE *NLS_GetFormats(LCID lcid, DWORD dwFlags)
150 /* GetLocaleInfo() identifiers for cached formatting strings */
151 static const LCTYPE NLS_LocaleIndices[] = {
152 LOCALE_SNEGATIVESIGN,
153 LOCALE_SLONGDATE, LOCALE_SSHORTDATE,
154 LOCALE_STIMEFORMAT,
155 LOCALE_SDAYNAME1, LOCALE_SDAYNAME2, LOCALE_SDAYNAME3,
156 LOCALE_SDAYNAME4, LOCALE_SDAYNAME5, LOCALE_SDAYNAME6, LOCALE_SDAYNAME7,
157 LOCALE_SABBREVDAYNAME1, LOCALE_SABBREVDAYNAME2, LOCALE_SABBREVDAYNAME3,
158 LOCALE_SABBREVDAYNAME4, LOCALE_SABBREVDAYNAME5, LOCALE_SABBREVDAYNAME6,
159 LOCALE_SABBREVDAYNAME7,
160 LOCALE_SMONTHNAME1, LOCALE_SMONTHNAME2, LOCALE_SMONTHNAME3,
161 LOCALE_SMONTHNAME4, LOCALE_SMONTHNAME5, LOCALE_SMONTHNAME6,
162 LOCALE_SMONTHNAME7, LOCALE_SMONTHNAME8, LOCALE_SMONTHNAME9,
163 LOCALE_SMONTHNAME10, LOCALE_SMONTHNAME11, LOCALE_SMONTHNAME12,
164 LOCALE_SMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES,
165 LOCALE_SMONTHNAME2 | LOCALE_RETURN_GENITIVE_NAMES,
166 LOCALE_SMONTHNAME3 | LOCALE_RETURN_GENITIVE_NAMES,
167 LOCALE_SMONTHNAME4 | LOCALE_RETURN_GENITIVE_NAMES,
168 LOCALE_SMONTHNAME5 | LOCALE_RETURN_GENITIVE_NAMES,
169 LOCALE_SMONTHNAME6 | LOCALE_RETURN_GENITIVE_NAMES,
170 LOCALE_SMONTHNAME7 | LOCALE_RETURN_GENITIVE_NAMES,
171 LOCALE_SMONTHNAME8 | LOCALE_RETURN_GENITIVE_NAMES,
172 LOCALE_SMONTHNAME9 | LOCALE_RETURN_GENITIVE_NAMES,
173 LOCALE_SMONTHNAME10 | LOCALE_RETURN_GENITIVE_NAMES,
174 LOCALE_SMONTHNAME11 | LOCALE_RETURN_GENITIVE_NAMES,
175 LOCALE_SMONTHNAME12 | LOCALE_RETURN_GENITIVE_NAMES,
176 LOCALE_SABBREVMONTHNAME1, LOCALE_SABBREVMONTHNAME2, LOCALE_SABBREVMONTHNAME3,
177 LOCALE_SABBREVMONTHNAME4, LOCALE_SABBREVMONTHNAME5, LOCALE_SABBREVMONTHNAME6,
178 LOCALE_SABBREVMONTHNAME7, LOCALE_SABBREVMONTHNAME8, LOCALE_SABBREVMONTHNAME9,
179 LOCALE_SABBREVMONTHNAME10, LOCALE_SABBREVMONTHNAME11, LOCALE_SABBREVMONTHNAME12,
180 LOCALE_S1159, LOCALE_S2359,
181 LOCALE_SYEARMONTH
183 static NLS_FORMAT_NODE *NLS_CachedFormats = NULL;
184 NLS_FORMAT_NODE *node = NLS_CachedFormats;
186 dwFlags &= LOCALE_NOUSEROVERRIDE;
188 TRACE("(0x%04lx,0x%08lx)\n", lcid, dwFlags);
190 /* See if we have already cached the locales number format */
191 while (node && (node->lcid != lcid || node->dwFlags != dwFlags) && node->next)
192 node = node->next;
194 if (!node || node->lcid != lcid || node->dwFlags != dwFlags)
196 NLS_FORMAT_NODE *new_node;
197 DWORD i;
199 TRACE("Creating new cache entry\n");
201 if (!(new_node = HeapAlloc(GetProcessHeap(), 0, sizeof(NLS_FORMAT_NODE))))
202 return NULL;
204 GET_LOCALE_NUMBER(new_node->dwCodePage, LOCALE_IDEFAULTANSICODEPAGE);
206 /* Number Format */
207 new_node->lcid = lcid;
208 new_node->dwFlags = dwFlags;
209 new_node->next = NULL;
211 GET_LOCALE_NUMBER(new_node->fmt.NumDigits, LOCALE_IDIGITS);
212 GET_LOCALE_NUMBER(new_node->fmt.LeadingZero, LOCALE_ILZERO);
213 GET_LOCALE_NUMBER(new_node->fmt.NegativeOrder, LOCALE_INEGNUMBER);
215 GET_LOCALE_NUMBER(new_node->fmt.Grouping, LOCALE_SGROUPING);
216 if (new_node->fmt.Grouping > 9 && new_node->fmt.Grouping != 32)
218 WARN("LOCALE_SGROUPING (%d) unhandled, please report!\n",
219 new_node->fmt.Grouping);
220 new_node->fmt.Grouping = 0;
223 GET_LOCALE_STRING(new_node->fmt.lpDecimalSep, LOCALE_SDECIMAL);
224 GET_LOCALE_STRING(new_node->fmt.lpThousandSep, LOCALE_STHOUSAND);
226 /* Currency Format */
227 new_node->cyfmt.NumDigits = new_node->fmt.NumDigits;
228 new_node->cyfmt.LeadingZero = new_node->fmt.LeadingZero;
230 GET_LOCALE_NUMBER(new_node->cyfmt.Grouping, LOCALE_SGROUPING);
232 if (new_node->cyfmt.Grouping > 9)
234 WARN("LOCALE_SMONGROUPING (%d) unhandled, please report!\n",
235 new_node->cyfmt.Grouping);
236 new_node->cyfmt.Grouping = 0;
239 GET_LOCALE_NUMBER(new_node->cyfmt.NegativeOrder, LOCALE_INEGCURR);
240 if (new_node->cyfmt.NegativeOrder > 15)
242 WARN("LOCALE_INEGCURR (%d) unhandled, please report!\n",
243 new_node->cyfmt.NegativeOrder);
244 new_node->cyfmt.NegativeOrder = 0;
246 GET_LOCALE_NUMBER(new_node->cyfmt.PositiveOrder, LOCALE_ICURRENCY);
247 if (new_node->cyfmt.PositiveOrder > 3)
249 WARN("LOCALE_IPOSCURR (%d) unhandled,please report!\n",
250 new_node->cyfmt.PositiveOrder);
251 new_node->cyfmt.PositiveOrder = 0;
253 GET_LOCALE_STRING(new_node->cyfmt.lpDecimalSep, LOCALE_SMONDECIMALSEP);
254 GET_LOCALE_STRING(new_node->cyfmt.lpThousandSep, LOCALE_SMONTHOUSANDSEP);
255 GET_LOCALE_STRING(new_node->cyfmt.lpCurrencySymbol, LOCALE_SCURRENCY);
257 /* Date/Time Format info, negative character, etc */
258 for (i = 0; i < ARRAY_SIZE(NLS_LocaleIndices); i++)
260 GET_LOCALE_STRING(new_node->lppszStrings[i], NLS_LocaleIndices[i]);
262 /* Save some memory if month genitive name is the same or not present */
263 for (i = 0; i < 12; i++)
265 if (wcscmp(GetLongMonth(new_node, i), GetGenitiveMonth(new_node, i)) == 0)
267 HeapFree(GetProcessHeap(), 0, GetGenitiveMonth(new_node, i));
268 GetGenitiveMonth(new_node, i) = NULL;
272 new_node->szShortAM[0] = GetAM(new_node)[0]; new_node->szShortAM[1] = '\0';
273 new_node->szShortPM[0] = GetPM(new_node)[0]; new_node->szShortPM[1] = '\0';
275 /* Now add the computed format to the cache */
276 RtlEnterCriticalSection(&NLS_FormatsCS);
278 /* Search again: We may have raced to add the node */
279 node = NLS_CachedFormats;
280 while (node && (node->lcid != lcid || node->dwFlags != dwFlags) && node->next)
281 node = node->next;
283 if (!node)
285 node = NLS_CachedFormats = new_node; /* Empty list */
286 new_node = NULL;
288 else if (node->lcid != lcid || node->dwFlags != dwFlags)
290 node->next = new_node; /* Not in the list, add to end */
291 node = new_node;
292 new_node = NULL;
295 RtlLeaveCriticalSection(&NLS_FormatsCS);
297 if (new_node)
299 /* We raced and lost: The node was already added by another thread.
300 * node points to the currently cached node, so free new_node.
302 for (i = 0; i < ARRAY_SIZE(NLS_LocaleIndices); i++)
303 HeapFree(GetProcessHeap(), 0, new_node->lppszStrings[i]);
304 HeapFree(GetProcessHeap(), 0, new_node->fmt.lpDecimalSep);
305 HeapFree(GetProcessHeap(), 0, new_node->fmt.lpThousandSep);
306 HeapFree(GetProcessHeap(), 0, new_node->cyfmt.lpDecimalSep);
307 HeapFree(GetProcessHeap(), 0, new_node->cyfmt.lpThousandSep);
308 HeapFree(GetProcessHeap(), 0, new_node->cyfmt.lpCurrencySymbol);
309 HeapFree(GetProcessHeap(), 0, new_node);
312 return node;
315 /**************************************************************************
316 * NLS_IsUnicodeOnlyLcid <internal>
318 * Determine if a locale is Unicode only, and thus invalid in ANSI calls.
320 static BOOL NLS_IsUnicodeOnlyLcid(LCID lcid)
322 lcid = ConvertDefaultLocale(lcid);
324 switch (PRIMARYLANGID(lcid))
326 case LANG_ARMENIAN:
327 case LANG_DIVEHI:
328 case LANG_GEORGIAN:
329 case LANG_GUJARATI:
330 case LANG_HINDI:
331 case LANG_KANNADA:
332 case LANG_KONKANI:
333 case LANG_MARATHI:
334 case LANG_PUNJABI:
335 case LANG_SANSKRIT:
336 TRACE("lcid 0x%08lx: langid 0x%04x is Unicode Only\n", lcid, PRIMARYLANGID(lcid));
337 return TRUE;
338 default:
339 return FALSE;
344 * Formatting of dates, times, numbers and currencies.
347 #define IsLiteralMarker(p) (p == '\'')
348 #define IsDateFmtChar(p) (p == 'd'||p == 'M'||p == 'y'||p == 'g')
349 #define IsTimeFmtChar(p) (p == 'H'||p == 'h'||p == 'm'||p == 's'||p == 't')
351 /* Only the following flags can be given if a date/time format is specified */
352 #define DATE_FORMAT_FLAGS (DATE_DATEVARSONLY)
353 #define TIME_FORMAT_FLAGS (TIME_TIMEVARSONLY|TIME_FORCE24HOURFORMAT| \
354 TIME_NOMINUTESORSECONDS|TIME_NOSECONDS| \
355 TIME_NOTIMEMARKER)
357 /******************************************************************************
358 * NLS_GetDateTimeFormatW <internal>
360 * Performs the formatting for GetDateFormatW/GetTimeFormatW.
362 * FIXME
363 * DATE_USE_ALT_CALENDAR - Requires GetCalendarInfo to work first.
364 * DATE_LTRREADING/DATE_RTLREADING - Not yet implemented.
366 static INT NLS_GetDateTimeFormatW(LCID lcid, DWORD dwFlags,
367 const SYSTEMTIME* lpTime, LPCWSTR lpFormat,
368 LPWSTR lpStr, INT cchOut)
370 const NLS_FORMAT_NODE *node;
371 SYSTEMTIME st;
372 INT cchWritten = 0;
373 INT lastFormatPos = 0;
374 BOOL bSkipping = FALSE; /* Skipping text around marker? */
375 BOOL d_dd_formatted = FALSE; /* previous formatted part was for d or dd */
377 /* Verify our arguments */
378 if ((cchOut && !lpStr) || !(node = NLS_GetFormats(lcid, dwFlags)))
379 goto invalid_parameter;
381 if (dwFlags & ~(DATE_DATEVARSONLY|TIME_TIMEVARSONLY))
383 if (lpFormat &&
384 ((dwFlags & DATE_DATEVARSONLY && dwFlags & ~DATE_FORMAT_FLAGS) ||
385 (dwFlags & TIME_TIMEVARSONLY && dwFlags & ~TIME_FORMAT_FLAGS)))
387 goto invalid_flags;
390 if (dwFlags & DATE_DATEVARSONLY)
392 if ((dwFlags & (DATE_LTRREADING|DATE_RTLREADING)) == (DATE_LTRREADING|DATE_RTLREADING))
393 goto invalid_flags;
394 else if (dwFlags & (DATE_LTRREADING|DATE_RTLREADING))
395 FIXME("Unsupported flags: DATE_LTRREADING/DATE_RTLREADING\n");
397 switch (dwFlags & (DATE_SHORTDATE|DATE_LONGDATE|DATE_YEARMONTH))
399 case 0:
400 break;
401 case DATE_SHORTDATE:
402 case DATE_LONGDATE:
403 case DATE_YEARMONTH:
404 if (lpFormat)
405 goto invalid_flags;
406 break;
407 default:
408 goto invalid_flags;
413 if (!lpFormat)
415 /* Use the appropriate default format */
416 if (dwFlags & DATE_DATEVARSONLY)
418 if (dwFlags & DATE_YEARMONTH)
419 lpFormat = GetYearMonth(node);
420 else if (dwFlags & DATE_LONGDATE)
421 lpFormat = GetLongDate(node);
422 else
423 lpFormat = GetShortDate(node);
425 else
426 lpFormat = GetTime(node);
429 if (!lpTime)
431 GetLocalTime(&st); /* Default to current time */
432 lpTime = &st;
434 else
436 if (dwFlags & DATE_DATEVARSONLY)
438 FILETIME ftTmp;
440 /* Verify the date and correct the D.O.W. if needed */
441 memset(&st, 0, sizeof(st));
442 st.wYear = lpTime->wYear;
443 st.wMonth = lpTime->wMonth;
444 st.wDay = lpTime->wDay;
446 if (st.wDay > 31 || st.wMonth > 12 || !SystemTimeToFileTime(&st, &ftTmp))
447 goto invalid_parameter;
449 FileTimeToSystemTime(&ftTmp, &st);
450 lpTime = &st;
453 if (dwFlags & TIME_TIMEVARSONLY)
455 /* Verify the time */
456 if (lpTime->wHour > 24 || lpTime->wMinute > 59 || lpTime->wSecond > 59)
457 goto invalid_parameter;
461 /* Format the output */
462 while (*lpFormat)
464 if (IsLiteralMarker(*lpFormat))
466 /* Start of a literal string */
467 lpFormat++;
469 /* Loop until the end of the literal marker or end of the string */
470 while (*lpFormat)
472 if (IsLiteralMarker(*lpFormat))
474 lpFormat++;
475 if (!IsLiteralMarker(*lpFormat))
476 break; /* Terminating literal marker */
479 if (!cchOut)
480 cchWritten++; /* Count size only */
481 else if (cchWritten >= cchOut)
482 goto overrun;
483 else if (!bSkipping)
485 lpStr[cchWritten] = *lpFormat;
486 cchWritten++;
488 lpFormat++;
491 else if ((dwFlags & DATE_DATEVARSONLY && IsDateFmtChar(*lpFormat)) ||
492 (dwFlags & TIME_TIMEVARSONLY && IsTimeFmtChar(*lpFormat)))
494 WCHAR buff[32], fmtChar;
495 LPCWSTR szAdd = NULL;
496 DWORD dwVal = 0;
497 int count = 0, dwLen;
499 bSkipping = FALSE;
501 fmtChar = *lpFormat;
502 while (*lpFormat == fmtChar)
504 count++;
505 lpFormat++;
507 buff[0] = '\0';
509 if (fmtChar != 'M') d_dd_formatted = FALSE;
510 switch(fmtChar)
512 case 'd':
513 if (count >= 4)
514 szAdd = GetLongDay(node, (lpTime->wDayOfWeek + 6) % 7);
515 else if (count == 3)
516 szAdd = GetShortDay(node, (lpTime->wDayOfWeek + 6) % 7);
517 else
519 dwVal = lpTime->wDay;
520 szAdd = buff;
521 d_dd_formatted = TRUE;
523 break;
525 case 'M':
526 if (count >= 4)
528 LPCWSTR genitive = GetGenitiveMonth(node, lpTime->wMonth - 1);
529 if (genitive)
531 if (d_dd_formatted)
533 szAdd = genitive;
534 break;
536 else
538 LPCWSTR format = lpFormat;
539 /* Look forward now, if next format pattern is for day genitive
540 name should be used */
541 while (*format)
543 /* Skip parts within markers */
544 if (IsLiteralMarker(*format))
546 ++format;
547 while (*format)
549 if (IsLiteralMarker(*format))
551 ++format;
552 if (!IsLiteralMarker(*format)) break;
556 if (*format != ' ') break;
557 ++format;
559 /* Only numeric day form matters */
560 if (*format == 'd')
562 INT dcount = 1;
563 while (*++format == 'd') dcount++;
564 if (dcount < 3)
566 szAdd = genitive;
567 break;
572 szAdd = GetLongMonth(node, lpTime->wMonth - 1);
574 else if (count == 3)
575 szAdd = GetShortMonth(node, lpTime->wMonth - 1);
576 else
578 dwVal = lpTime->wMonth;
579 szAdd = buff;
581 break;
583 case 'y':
584 if (count >= 4)
586 count = 4;
587 dwVal = lpTime->wYear;
589 else
591 count = count > 2 ? 2 : count;
592 dwVal = lpTime->wYear % 100;
594 szAdd = buff;
595 break;
597 case 'g':
598 if (count == 2)
600 /* FIXME: Our GetCalendarInfo() does not yet support CAL_SERASTRING.
601 * When it is fixed, this string should be cached in 'node'.
603 FIXME("Should be using GetCalendarInfo(CAL_SERASTRING), defaulting to 'AD'\n");
604 buff[0] = 'A'; buff[1] = 'D'; buff[2] = '\0';
606 else
608 buff[0] = 'g'; buff[1] = '\0'; /* Add a literal 'g' */
610 szAdd = buff;
611 break;
613 case 'h':
614 if (!(dwFlags & TIME_FORCE24HOURFORMAT))
616 count = count > 2 ? 2 : count;
617 dwVal = lpTime->wHour == 0 ? 12 : (lpTime->wHour - 1) % 12 + 1;
618 szAdd = buff;
619 break;
621 /* .. fall through if we are forced to output in 24 hour format */
623 case 'H':
624 count = count > 2 ? 2 : count;
625 dwVal = lpTime->wHour;
626 szAdd = buff;
627 break;
629 case 'm':
630 if (dwFlags & TIME_NOMINUTESORSECONDS)
632 cchWritten = lastFormatPos; /* Skip */
633 bSkipping = TRUE;
635 else
637 count = count > 2 ? 2 : count;
638 dwVal = lpTime->wMinute;
639 szAdd = buff;
641 break;
643 case 's':
644 if (dwFlags & (TIME_NOSECONDS|TIME_NOMINUTESORSECONDS))
646 cchWritten = lastFormatPos; /* Skip */
647 bSkipping = TRUE;
649 else
651 count = count > 2 ? 2 : count;
652 dwVal = lpTime->wSecond;
653 szAdd = buff;
655 break;
657 case 't':
658 if (dwFlags & TIME_NOTIMEMARKER)
660 cchWritten = lastFormatPos; /* Skip */
661 bSkipping = TRUE;
663 else
665 if (count == 1)
666 szAdd = lpTime->wHour < 12 ? node->szShortAM : node->szShortPM;
667 else
668 szAdd = lpTime->wHour < 12 ? GetAM(node) : GetPM(node);
670 break;
673 if (szAdd == buff && buff[0] == '\0')
675 /* We have a numeric value to add */
676 swprintf(buff, ARRAY_SIZE(buff), L"%.*d", count, dwVal);
679 dwLen = szAdd ? lstrlenW(szAdd) : 0;
681 if (cchOut && dwLen)
683 if (cchWritten + dwLen < cchOut)
684 memcpy(lpStr + cchWritten, szAdd, dwLen * sizeof(WCHAR));
685 else
687 memcpy(lpStr + cchWritten, szAdd, (cchOut - cchWritten) * sizeof(WCHAR));
688 goto overrun;
691 cchWritten += dwLen;
692 lastFormatPos = cchWritten; /* Save position of last output format text */
694 else
696 /* Literal character */
697 if (!cchOut)
698 cchWritten++; /* Count size only */
699 else if (cchWritten >= cchOut)
700 goto overrun;
701 else if (!bSkipping || *lpFormat == ' ')
703 lpStr[cchWritten] = *lpFormat;
704 cchWritten++;
706 lpFormat++;
710 /* Final string terminator and sanity check */
711 if (cchOut)
713 if (cchWritten >= cchOut)
714 goto overrun;
715 else
716 lpStr[cchWritten] = '\0';
718 cchWritten++; /* Include terminating NUL */
720 TRACE("returning length=%d, output=%s\n", cchWritten, debugstr_w(lpStr));
721 return cchWritten;
723 overrun:
724 TRACE("returning 0, (ERROR_INSUFFICIENT_BUFFER)\n");
725 SetLastError(ERROR_INSUFFICIENT_BUFFER);
726 return 0;
728 invalid_parameter:
729 SetLastError(ERROR_INVALID_PARAMETER);
730 return 0;
732 invalid_flags:
733 SetLastError(ERROR_INVALID_FLAGS);
734 return 0;
737 /******************************************************************************
738 * NLS_GetDateTimeFormatA <internal>
740 * ANSI wrapper for GetDateFormatA/GetTimeFormatA.
742 static INT NLS_GetDateTimeFormatA(LCID lcid, DWORD dwFlags,
743 const SYSTEMTIME* lpTime,
744 LPCSTR lpFormat, LPSTR lpStr, INT cchOut)
746 DWORD cp = CP_ACP;
747 WCHAR szFormat[128], szOut[128];
748 INT iRet, cchOutW;
750 TRACE("(0x%04lx,0x%08lx,%p,%s,%p,%d)\n", lcid, dwFlags, lpTime,
751 debugstr_a(lpFormat), lpStr, cchOut);
753 if ((cchOut && !lpStr) || NLS_IsUnicodeOnlyLcid(lcid))
755 SetLastError(ERROR_INVALID_PARAMETER);
756 return 0;
759 if (!(dwFlags & LOCALE_USE_CP_ACP))
761 const NLS_FORMAT_NODE *node = NLS_GetFormats(lcid, dwFlags);
762 if (!node)
764 SetLastError(ERROR_INVALID_PARAMETER);
765 return 0;
768 cp = node->dwCodePage;
771 if (lpFormat)
772 MultiByteToWideChar(cp, 0, lpFormat, -1, szFormat, ARRAY_SIZE(szFormat));
774 /* If cchOut == 0 we need the full string to get the accurate ANSI size */
775 cchOutW = (cchOut && cchOut <= ARRAY_SIZE(szOut)) ? cchOut : ARRAY_SIZE(szOut);
776 iRet = NLS_GetDateTimeFormatW(lcid, dwFlags, lpTime, lpFormat ? szFormat : NULL,
777 szOut, cchOutW);
778 if (iRet)
779 iRet = WideCharToMultiByte(cp, 0, szOut, -1, lpStr, cchOut, NULL, NULL);
780 return iRet;
783 /******************************************************************************
784 * GetDateFormatA [KERNEL32.@]
786 * Format a date for a given locale.
788 * PARAMS
789 * lcid [I] Locale to format for
790 * dwFlags [I] LOCALE_ and DATE_ flags from "winnls.h"
791 * lpTime [I] Date to format
792 * lpFormat [I] Format string, or NULL to use the system defaults
793 * lpDateStr [O] Destination for formatted string
794 * cchOut [I] Size of lpDateStr, or 0 to calculate the resulting size
796 * NOTES
797 * - If lpFormat is NULL, lpDateStr will be formatted according to the format
798 * details returned by GetLocaleInfoA() and modified by dwFlags.
799 * - lpFormat is a string of characters and formatting tokens. Any characters
800 * in the string are copied verbatim to lpDateStr, with tokens being replaced
801 * by the date values they represent.
802 * - The following tokens have special meanings in a date format string:
803 *| Token Meaning
804 *| ----- -------
805 *| d Single digit day of the month (no leading 0)
806 *| dd Double digit day of the month
807 *| ddd Short name for the day of the week
808 *| dddd Long name for the day of the week
809 *| M Single digit month of the year (no leading 0)
810 *| MM Double digit month of the year
811 *| MMM Short name for the month of the year
812 *| MMMM Long name for the month of the year
813 *| y Double digit year number (no leading 0)
814 *| yy Double digit year number
815 *| yyyy Four digit year number
816 *| gg Era string, for example 'AD'.
817 * - To output any literal character that could be misidentified as a token,
818 * enclose it in single quotes.
819 * - The ANSI version of this function fails if lcid is Unicode only.
821 * RETURNS
822 * Success: The number of character written to lpDateStr, or that would
823 * have been written, if cchOut is 0.
824 * Failure: 0. Use GetLastError() to determine the cause.
826 INT WINAPI GetDateFormatA( LCID lcid, DWORD dwFlags, const SYSTEMTIME* lpTime,
827 LPCSTR lpFormat, LPSTR lpDateStr, INT cchOut)
829 TRACE("(0x%04lx,0x%08lx,%p,%s,%p,%d)\n",lcid, dwFlags, lpTime,
830 debugstr_a(lpFormat), lpDateStr, cchOut);
832 return NLS_GetDateTimeFormatA(lcid, dwFlags | DATE_DATEVARSONLY, lpTime,
833 lpFormat, lpDateStr, cchOut);
836 /******************************************************************************
837 * GetDateFormatEx [KERNEL32.@]
839 * Format a date for a given locale.
841 * PARAMS
842 * localename [I] Locale to format for
843 * flags [I] LOCALE_ and DATE_ flags from "winnls.h"
844 * date [I] Date to format
845 * format [I] Format string, or NULL to use the locale defaults
846 * outbuf [O] Destination for formatted string
847 * bufsize [I] Size of outbuf, or 0 to calculate the resulting size
848 * calendar [I] Reserved, must be NULL
850 * See GetDateFormatA for notes.
852 * RETURNS
853 * Success: The number of characters written to outbuf, or that would have
854 * been written if bufsize is 0.
855 * Failure: 0. Use GetLastError() to determine the cause.
857 INT WINAPI GetDateFormatEx(LPCWSTR localename, DWORD flags,
858 const SYSTEMTIME* date, LPCWSTR format,
859 LPWSTR outbuf, INT bufsize, LPCWSTR calendar)
861 TRACE("(%s,0x%08lx,%p,%s,%p,%d,%s)\n", debugstr_w(localename), flags,
862 date, debugstr_w(format), outbuf, bufsize, debugstr_w(calendar));
864 /* Parameter is currently reserved and Windows errors if set */
865 if (calendar != NULL)
867 SetLastError(ERROR_INVALID_PARAMETER);
868 return 0;
871 return NLS_GetDateTimeFormatW(LocaleNameToLCID(localename, 0),
872 flags | DATE_DATEVARSONLY, date, format,
873 outbuf, bufsize);
876 /******************************************************************************
877 * GetDateFormatW [KERNEL32.@]
879 * See GetDateFormatA.
881 INT WINAPI GetDateFormatW(LCID lcid, DWORD dwFlags, const SYSTEMTIME* lpTime,
882 LPCWSTR lpFormat, LPWSTR lpDateStr, INT cchOut)
884 TRACE("(0x%04lx,0x%08lx,%p,%s,%p,%d)\n", lcid, dwFlags, lpTime,
885 debugstr_w(lpFormat), lpDateStr, cchOut);
887 return NLS_GetDateTimeFormatW(lcid, dwFlags|DATE_DATEVARSONLY, lpTime,
888 lpFormat, lpDateStr, cchOut);
891 /******************************************************************************
892 * GetTimeFormatA [KERNEL32.@]
894 * Format a time for a given locale.
896 * PARAMS
897 * lcid [I] Locale to format for
898 * dwFlags [I] LOCALE_ and TIME_ flags from "winnls.h"
899 * lpTime [I] Time to format
900 * lpFormat [I] Formatting overrides
901 * lpTimeStr [O] Destination for formatted string
902 * cchOut [I] Size of lpTimeStr, or 0 to calculate the resulting size
904 * NOTES
905 * - If lpFormat is NULL, lpszValue will be formatted according to the format
906 * details returned by GetLocaleInfoA() and modified by dwFlags.
907 * - lpFormat is a string of characters and formatting tokens. Any characters
908 * in the string are copied verbatim to lpTimeStr, with tokens being replaced
909 * by the time values they represent.
910 * - The following tokens have special meanings in a time format string:
911 *| Token Meaning
912 *| ----- -------
913 *| h Hours with no leading zero (12-hour clock)
914 *| hh Hours with full two digits (12-hour clock)
915 *| H Hours with no leading zero (24-hour clock)
916 *| HH Hours with full two digits (24-hour clock)
917 *| m Minutes with no leading zero
918 *| mm Minutes with full two digits
919 *| s Seconds with no leading zero
920 *| ss Seconds with full two digits
921 *| t Short time marker (e.g. "A" or "P")
922 *| tt Long time marker (e.g. "AM", "PM")
923 * - To output any literal character that could be misidentified as a token,
924 * enclose it in single quotes.
925 * - The ANSI version of this function fails if lcid is Unicode only.
927 * RETURNS
928 * Success: The number of character written to lpTimeStr, or that would
929 * have been written, if cchOut is 0.
930 * Failure: 0. Use GetLastError() to determine the cause.
932 INT WINAPI GetTimeFormatA(LCID lcid, DWORD dwFlags, const SYSTEMTIME* lpTime,
933 LPCSTR lpFormat, LPSTR lpTimeStr, INT cchOut)
935 TRACE("(0x%04lx,0x%08lx,%p,%s,%p,%d)\n",lcid, dwFlags, lpTime,
936 debugstr_a(lpFormat), lpTimeStr, cchOut);
938 return NLS_GetDateTimeFormatA(lcid, dwFlags|TIME_TIMEVARSONLY, lpTime,
939 lpFormat, lpTimeStr, cchOut);
942 /******************************************************************************
943 * GetTimeFormatEx [KERNEL32.@]
945 * Format a date for a given locale.
947 * PARAMS
948 * localename [I] Locale to format for
949 * flags [I] LOCALE_ and TIME_ flags from "winnls.h"
950 * time [I] Time to format
951 * format [I] Formatting overrides
952 * outbuf [O] Destination for formatted string
953 * bufsize [I] Size of outbuf, or 0 to calculate the resulting size
955 * See GetTimeFormatA for notes.
957 * RETURNS
958 * Success: The number of characters written to outbuf, or that would have
959 * have been written if bufsize is 0.
960 * Failure: 0. Use GetLastError() to determine the cause.
962 INT WINAPI GetTimeFormatEx(LPCWSTR localename, DWORD flags,
963 const SYSTEMTIME* time, LPCWSTR format,
964 LPWSTR outbuf, INT bufsize)
966 TRACE("(%s,0x%08lx,%p,%s,%p,%d)\n", debugstr_w(localename), flags, time,
967 debugstr_w(format), outbuf, bufsize);
969 return NLS_GetDateTimeFormatW(LocaleNameToLCID(localename, 0),
970 flags | TIME_TIMEVARSONLY, time, format,
971 outbuf, bufsize);
974 /******************************************************************************
975 * GetTimeFormatW [KERNEL32.@]
977 * See GetTimeFormatA.
979 INT WINAPI GetTimeFormatW(LCID lcid, DWORD dwFlags, const SYSTEMTIME* lpTime,
980 LPCWSTR lpFormat, LPWSTR lpTimeStr, INT cchOut)
982 TRACE("(0x%04lx,0x%08lx,%p,%s,%p,%d)\n",lcid, dwFlags, lpTime,
983 debugstr_w(lpFormat), lpTimeStr, cchOut);
985 return NLS_GetDateTimeFormatW(lcid, dwFlags|TIME_TIMEVARSONLY, lpTime,
986 lpFormat, lpTimeStr, cchOut);
989 /* Number parsing state flags */
990 #define NF_ISNEGATIVE 0x1 /* '-' found */
991 #define NF_ISREAL 0x2 /* '.' found */
992 #define NF_DIGITS 0x4 /* '0'-'9' found */
993 #define NF_DIGITS_OUT 0x8 /* Digits before the '.' found */
994 #define NF_ROUND 0x10 /* Number needs to be rounded */
996 /* Formatting options for Numbers */
997 #define NLS_NEG_PARENS 0 /* "(1.1)" */
998 #define NLS_NEG_LEFT 1 /* "-1.1" */
999 #define NLS_NEG_LEFT_SPACE 2 /* "- 1.1" */
1000 #define NLS_NEG_RIGHT 3 /* "1.1-" */
1001 #define NLS_NEG_RIGHT_SPACE 4 /* "1.1 -" */
1003 /**************************************************************************
1004 * GetNumberFormatW (KERNEL32.@)
1006 * See GetNumberFormatA.
1008 INT WINAPI GetNumberFormatW(LCID lcid, DWORD dwFlags,
1009 LPCWSTR lpszValue, const NUMBERFMTW *lpFormat,
1010 LPWSTR lpNumberStr, int cchOut)
1012 WCHAR szBuff[128], *szOut = szBuff + ARRAY_SIZE(szBuff) - 1;
1013 WCHAR szNegBuff[8];
1014 const WCHAR *lpszNeg = NULL, *lpszNegStart, *szSrc;
1015 DWORD dwState = 0, dwDecimals = 0, dwGroupCount = 0, dwCurrentGroupCount = 0;
1016 INT iRet;
1018 TRACE("(0x%04lx,0x%08lx,%s,%p,%p,%d)\n", lcid, dwFlags, debugstr_w(lpszValue),
1019 lpFormat, lpNumberStr, cchOut);
1021 lcid = ConvertDefaultLocale(lcid);
1022 if (!lpszValue || cchOut < 0 || (cchOut > 0 && !lpNumberStr) ||
1023 !IsValidLocale(lcid, 0) ||
1024 (lpFormat && (dwFlags || !lpFormat->lpDecimalSep || !lpFormat->lpThousandSep)))
1026 goto error;
1029 if (!lpFormat)
1031 const NLS_FORMAT_NODE *node = NLS_GetFormats(lcid, dwFlags);
1033 if (!node)
1034 goto error;
1035 lpFormat = &node->fmt;
1036 lpszNegStart = lpszNeg = GetNegative(node);
1038 else
1040 GetLocaleInfoW(lcid, LOCALE_SNEGATIVESIGN|(dwFlags & LOCALE_NOUSEROVERRIDE),
1041 szNegBuff, ARRAY_SIZE(szNegBuff));
1042 lpszNegStart = lpszNeg = szNegBuff;
1044 lpszNeg = lpszNeg + lstrlenW(lpszNeg) - 1;
1046 dwFlags &= (LOCALE_NOUSEROVERRIDE|LOCALE_USE_CP_ACP);
1048 /* Format the number backwards into a temporary buffer */
1050 szSrc = lpszValue;
1051 *szOut-- = '\0';
1053 /* Check the number for validity */
1054 while (*szSrc)
1056 if (*szSrc >= '0' && *szSrc <= '9')
1058 dwState |= NF_DIGITS;
1059 if (dwState & NF_ISREAL)
1060 dwDecimals++;
1062 else if (*szSrc == '-')
1064 if (dwState)
1065 goto error; /* '-' not first character */
1066 dwState |= NF_ISNEGATIVE;
1068 else if (*szSrc == '.')
1070 if (dwState & NF_ISREAL)
1071 goto error; /* More than one '.' */
1072 dwState |= NF_ISREAL;
1074 else
1075 goto error; /* Invalid char */
1076 szSrc++;
1078 szSrc--; /* Point to last character */
1080 if (!(dwState & NF_DIGITS))
1081 goto error; /* No digits */
1083 /* Add any trailing negative sign */
1084 if (dwState & NF_ISNEGATIVE)
1086 switch (lpFormat->NegativeOrder)
1088 case NLS_NEG_PARENS:
1089 *szOut-- = ')';
1090 break;
1091 case NLS_NEG_RIGHT:
1092 case NLS_NEG_RIGHT_SPACE:
1093 while (lpszNeg >= lpszNegStart)
1094 *szOut-- = *lpszNeg--;
1095 if (lpFormat->NegativeOrder == NLS_NEG_RIGHT_SPACE)
1096 *szOut-- = ' ';
1097 break;
1101 /* Copy all digits up to the decimal point */
1102 if (!lpFormat->NumDigits)
1104 if (dwState & NF_ISREAL)
1106 while (*szSrc != '.') /* Don't write any decimals or a separator */
1108 if (*szSrc >= '5' || (*szSrc == '4' && (dwState & NF_ROUND)))
1109 dwState |= NF_ROUND;
1110 else
1111 dwState &= ~NF_ROUND;
1112 szSrc--;
1114 szSrc--;
1117 else
1119 LPWSTR lpszDec = lpFormat->lpDecimalSep + lstrlenW(lpFormat->lpDecimalSep) - 1;
1121 if (dwDecimals <= lpFormat->NumDigits)
1123 dwDecimals = lpFormat->NumDigits - dwDecimals;
1124 while (dwDecimals--)
1125 *szOut-- = '0'; /* Pad to correct number of dp */
1127 else
1129 dwDecimals -= lpFormat->NumDigits;
1130 /* Skip excess decimals, and determine if we have to round the number */
1131 while (dwDecimals--)
1133 if (*szSrc >= '5' || (*szSrc == '4' && (dwState & NF_ROUND)))
1134 dwState |= NF_ROUND;
1135 else
1136 dwState &= ~NF_ROUND;
1137 szSrc--;
1141 if (dwState & NF_ISREAL)
1143 while (*szSrc != '.')
1145 if (dwState & NF_ROUND)
1147 if (*szSrc == '9')
1148 *szOut-- = '0'; /* continue rounding */
1149 else
1151 dwState &= ~NF_ROUND;
1152 *szOut-- = (*szSrc)+1;
1154 szSrc--;
1156 else
1157 *szOut-- = *szSrc--; /* Write existing decimals */
1159 szSrc--; /* Skip '.' */
1162 while (lpszDec >= lpFormat->lpDecimalSep)
1163 *szOut-- = *lpszDec--; /* Write decimal separator */
1166 dwGroupCount = lpFormat->Grouping == 32 ? 3 : lpFormat->Grouping;
1168 /* Write the remaining whole number digits, including grouping chars */
1169 while (szSrc >= lpszValue && *szSrc >= '0' && *szSrc <= '9')
1171 if (dwState & NF_ROUND)
1173 if (*szSrc == '9')
1174 *szOut-- = '0'; /* continue rounding */
1175 else
1177 dwState &= ~NF_ROUND;
1178 *szOut-- = (*szSrc)+1;
1180 szSrc--;
1182 else
1183 *szOut-- = *szSrc--;
1185 dwState |= NF_DIGITS_OUT;
1186 dwCurrentGroupCount++;
1187 if (szSrc >= lpszValue && dwCurrentGroupCount == dwGroupCount && *szSrc != '-')
1189 LPWSTR lpszGrp = lpFormat->lpThousandSep + lstrlenW(lpFormat->lpThousandSep) - 1;
1191 while (lpszGrp >= lpFormat->lpThousandSep)
1192 *szOut-- = *lpszGrp--; /* Write grouping char */
1194 dwCurrentGroupCount = 0;
1195 if (lpFormat->Grouping == 32)
1196 dwGroupCount = 2; /* Indic grouping: 3 then 2 */
1199 if (dwState & NF_ROUND)
1201 *szOut-- = '1'; /* e.g. .6 > 1.0 */
1203 else if (!(dwState & NF_DIGITS_OUT) && lpFormat->LeadingZero)
1204 *szOut-- = '0'; /* Add leading 0 if we have no digits before the decimal point */
1206 /* Add any leading negative sign */
1207 if (dwState & NF_ISNEGATIVE)
1209 switch (lpFormat->NegativeOrder)
1211 case NLS_NEG_PARENS:
1212 *szOut-- = '(';
1213 break;
1214 case NLS_NEG_LEFT_SPACE:
1215 *szOut-- = ' ';
1216 /* Fall through */
1217 case NLS_NEG_LEFT:
1218 while (lpszNeg >= lpszNegStart)
1219 *szOut-- = *lpszNeg--;
1220 break;
1223 szOut++;
1225 iRet = lstrlenW(szOut) + 1;
1226 if (cchOut)
1228 if (iRet <= cchOut)
1229 memcpy(lpNumberStr, szOut, iRet * sizeof(WCHAR));
1230 else
1232 memcpy(lpNumberStr, szOut, cchOut * sizeof(WCHAR));
1233 lpNumberStr[cchOut - 1] = '\0';
1234 SetLastError(ERROR_INSUFFICIENT_BUFFER);
1235 iRet = 0;
1238 return iRet;
1240 error:
1241 SetLastError(lpFormat && dwFlags ? ERROR_INVALID_FLAGS : ERROR_INVALID_PARAMETER);
1242 return 0;
1245 /**************************************************************************
1246 * GetNumberFormatEx (KERNEL32.@)
1248 INT WINAPI GetNumberFormatEx(LPCWSTR name, DWORD flags,
1249 LPCWSTR value, const NUMBERFMTW *format,
1250 LPWSTR number, int numout)
1252 LCID lcid;
1254 TRACE("(%s,0x%08lx,%s,%p,%p,%d)\n", debugstr_w(name), flags,
1255 debugstr_w(value), format, number, numout);
1257 lcid = LocaleNameToLCID(name, 0);
1258 if (!lcid)
1259 return 0;
1261 return GetNumberFormatW(lcid, flags, value, format, number, numout);
1264 /* Formatting states for Currencies. We use flags to avoid code duplication. */
1265 #define CF_PARENS 0x1 /* Parentheses */
1266 #define CF_MINUS_LEFT 0x2 /* '-' to the left */
1267 #define CF_MINUS_RIGHT 0x4 /* '-' to the right */
1268 #define CF_MINUS_BEFORE 0x8 /* '-' before '$' */
1269 #define CF_CY_LEFT 0x10 /* '$' to the left */
1270 #define CF_CY_RIGHT 0x20 /* '$' to the right */
1271 #define CF_CY_SPACE 0x40 /* ' ' by '$' */
1273 /**************************************************************************
1274 * GetCurrencyFormatW (KERNEL32.@)
1276 * See GetCurrencyFormatA.
1278 INT WINAPI GetCurrencyFormatW(LCID lcid, DWORD dwFlags,
1279 LPCWSTR lpszValue, const CURRENCYFMTW *lpFormat,
1280 LPWSTR lpCurrencyStr, int cchOut)
1282 static const BYTE NLS_NegCyFormats[16] =
1284 CF_PARENS|CF_CY_LEFT, /* ($1.1) */
1285 CF_MINUS_LEFT|CF_MINUS_BEFORE|CF_CY_LEFT, /* -$1.1 */
1286 CF_MINUS_LEFT|CF_CY_LEFT, /* $-1.1 */
1287 CF_MINUS_RIGHT|CF_CY_LEFT, /* $1.1- */
1288 CF_PARENS|CF_CY_RIGHT, /* (1.1$) */
1289 CF_MINUS_LEFT|CF_CY_RIGHT, /* -1.1$ */
1290 CF_MINUS_RIGHT|CF_MINUS_BEFORE|CF_CY_RIGHT, /* 1.1-$ */
1291 CF_MINUS_RIGHT|CF_CY_RIGHT, /* 1.1$- */
1292 CF_MINUS_LEFT|CF_CY_RIGHT|CF_CY_SPACE, /* -1.1 $ */
1293 CF_MINUS_LEFT|CF_MINUS_BEFORE|CF_CY_LEFT|CF_CY_SPACE, /* -$ 1.1 */
1294 CF_MINUS_RIGHT|CF_CY_RIGHT|CF_CY_SPACE, /* 1.1 $- */
1295 CF_MINUS_RIGHT|CF_CY_LEFT|CF_CY_SPACE, /* $ 1.1- */
1296 CF_MINUS_LEFT|CF_CY_LEFT|CF_CY_SPACE, /* $ -1.1 */
1297 CF_MINUS_RIGHT|CF_MINUS_BEFORE|CF_CY_RIGHT|CF_CY_SPACE, /* 1.1- $ */
1298 CF_PARENS|CF_CY_LEFT|CF_CY_SPACE, /* ($ 1.1) */
1299 CF_PARENS|CF_CY_RIGHT|CF_CY_SPACE, /* (1.1 $) */
1301 static const BYTE NLS_PosCyFormats[4] =
1303 CF_CY_LEFT, /* $1.1 */
1304 CF_CY_RIGHT, /* 1.1$ */
1305 CF_CY_LEFT|CF_CY_SPACE, /* $ 1.1 */
1306 CF_CY_RIGHT|CF_CY_SPACE, /* 1.1 $ */
1308 WCHAR szBuff[128], *szOut = szBuff + ARRAY_SIZE(szBuff) - 1;
1309 WCHAR szNegBuff[8];
1310 const WCHAR *lpszNeg = NULL, *lpszNegStart, *szSrc, *lpszCy, *lpszCyStart;
1311 DWORD dwState = 0, dwDecimals = 0, dwGroupCount = 0, dwCurrentGroupCount = 0, dwFmt;
1312 INT iRet;
1314 TRACE("(0x%04lx,0x%08lx,%s,%p,%p,%d)\n", lcid, dwFlags, debugstr_w(lpszValue),
1315 lpFormat, lpCurrencyStr, cchOut);
1317 lcid = ConvertDefaultLocale(lcid);
1318 if (!lpszValue || cchOut < 0 || (cchOut > 0 && !lpCurrencyStr) ||
1319 !IsValidLocale(lcid, 0) ||
1320 (lpFormat && (dwFlags || !lpFormat->lpDecimalSep || !lpFormat->lpThousandSep ||
1321 !lpFormat->lpCurrencySymbol || lpFormat->NegativeOrder > 15 ||
1322 lpFormat->PositiveOrder > 3)))
1324 goto error;
1327 if (!lpFormat)
1329 const NLS_FORMAT_NODE *node = NLS_GetFormats(lcid, dwFlags);
1331 if (!node)
1332 goto error;
1334 lpFormat = &node->cyfmt;
1335 lpszNegStart = lpszNeg = GetNegative(node);
1337 else
1339 GetLocaleInfoW(lcid, LOCALE_SNEGATIVESIGN|(dwFlags & LOCALE_NOUSEROVERRIDE),
1340 szNegBuff, ARRAY_SIZE(szNegBuff));
1341 lpszNegStart = lpszNeg = szNegBuff;
1343 dwFlags &= (LOCALE_NOUSEROVERRIDE|LOCALE_USE_CP_ACP);
1345 lpszNeg = lpszNeg + lstrlenW(lpszNeg) - 1;
1346 lpszCyStart = lpFormat->lpCurrencySymbol;
1347 lpszCy = lpszCyStart + lstrlenW(lpszCyStart) - 1;
1349 /* Format the currency backwards into a temporary buffer */
1351 szSrc = lpszValue;
1352 *szOut-- = '\0';
1354 /* Check the number for validity */
1355 while (*szSrc)
1357 if (*szSrc >= '0' && *szSrc <= '9')
1359 dwState |= NF_DIGITS;
1360 if (dwState & NF_ISREAL)
1361 dwDecimals++;
1363 else if (*szSrc == '-')
1365 if (dwState)
1366 goto error; /* '-' not first character */
1367 dwState |= NF_ISNEGATIVE;
1369 else if (*szSrc == '.')
1371 if (dwState & NF_ISREAL)
1372 goto error; /* More than one '.' */
1373 dwState |= NF_ISREAL;
1375 else
1376 goto error; /* Invalid char */
1377 szSrc++;
1379 szSrc--; /* Point to last character */
1381 if (!(dwState & NF_DIGITS))
1382 goto error; /* No digits */
1384 if (dwState & NF_ISNEGATIVE)
1385 dwFmt = NLS_NegCyFormats[lpFormat->NegativeOrder];
1386 else
1387 dwFmt = NLS_PosCyFormats[lpFormat->PositiveOrder];
1389 /* Add any trailing negative or currency signs */
1390 if (dwFmt & CF_PARENS)
1391 *szOut-- = ')';
1393 while (dwFmt & (CF_MINUS_RIGHT|CF_CY_RIGHT))
1395 switch (dwFmt & (CF_MINUS_RIGHT|CF_MINUS_BEFORE|CF_CY_RIGHT))
1397 case CF_MINUS_RIGHT:
1398 case CF_MINUS_RIGHT|CF_CY_RIGHT:
1399 while (lpszNeg >= lpszNegStart)
1400 *szOut-- = *lpszNeg--;
1401 dwFmt &= ~CF_MINUS_RIGHT;
1402 break;
1404 case CF_CY_RIGHT:
1405 case CF_MINUS_BEFORE|CF_CY_RIGHT:
1406 case CF_MINUS_RIGHT|CF_MINUS_BEFORE|CF_CY_RIGHT:
1407 while (lpszCy >= lpszCyStart)
1408 *szOut-- = *lpszCy--;
1409 if (dwFmt & CF_CY_SPACE)
1410 *szOut-- = ' ';
1411 dwFmt &= ~(CF_CY_RIGHT|CF_MINUS_BEFORE);
1412 break;
1416 /* Copy all digits up to the decimal point */
1417 if (!lpFormat->NumDigits)
1419 if (dwState & NF_ISREAL)
1421 while (*szSrc != '.') /* Don't write any decimals or a separator */
1423 if (*szSrc >= '5' || (*szSrc == '4' && (dwState & NF_ROUND)))
1424 dwState |= NF_ROUND;
1425 else
1426 dwState &= ~NF_ROUND;
1427 szSrc--;
1429 szSrc--;
1432 else
1434 LPWSTR lpszDec = lpFormat->lpDecimalSep + lstrlenW(lpFormat->lpDecimalSep) - 1;
1436 if (dwDecimals <= lpFormat->NumDigits)
1438 dwDecimals = lpFormat->NumDigits - dwDecimals;
1439 while (dwDecimals--)
1440 *szOut-- = '0'; /* Pad to correct number of dp */
1442 else
1444 dwDecimals -= lpFormat->NumDigits;
1445 /* Skip excess decimals, and determine if we have to round the number */
1446 while (dwDecimals--)
1448 if (*szSrc >= '5' || (*szSrc == '4' && (dwState & NF_ROUND)))
1449 dwState |= NF_ROUND;
1450 else
1451 dwState &= ~NF_ROUND;
1452 szSrc--;
1456 if (dwState & NF_ISREAL)
1458 while (*szSrc != '.')
1460 if (dwState & NF_ROUND)
1462 if (*szSrc == '9')
1463 *szOut-- = '0'; /* continue rounding */
1464 else
1466 dwState &= ~NF_ROUND;
1467 *szOut-- = (*szSrc)+1;
1469 szSrc--;
1471 else
1472 *szOut-- = *szSrc--; /* Write existing decimals */
1474 szSrc--; /* Skip '.' */
1476 while (lpszDec >= lpFormat->lpDecimalSep)
1477 *szOut-- = *lpszDec--; /* Write decimal separator */
1480 dwGroupCount = lpFormat->Grouping;
1482 /* Write the remaining whole number digits, including grouping chars */
1483 while (szSrc >= lpszValue && *szSrc >= '0' && *szSrc <= '9')
1485 if (dwState & NF_ROUND)
1487 if (*szSrc == '9')
1488 *szOut-- = '0'; /* continue rounding */
1489 else
1491 dwState &= ~NF_ROUND;
1492 *szOut-- = (*szSrc)+1;
1494 szSrc--;
1496 else
1497 *szOut-- = *szSrc--;
1499 dwState |= NF_DIGITS_OUT;
1500 dwCurrentGroupCount++;
1501 if (szSrc >= lpszValue && dwCurrentGroupCount == dwGroupCount && *szSrc != '-')
1503 LPWSTR lpszGrp = lpFormat->lpThousandSep + lstrlenW(lpFormat->lpThousandSep) - 1;
1505 while (lpszGrp >= lpFormat->lpThousandSep)
1506 *szOut-- = *lpszGrp--; /* Write grouping char */
1508 dwCurrentGroupCount = 0;
1511 if (dwState & NF_ROUND)
1512 *szOut-- = '1'; /* e.g. .6 > 1.0 */
1513 else if (!(dwState & NF_DIGITS_OUT) && lpFormat->LeadingZero)
1514 *szOut-- = '0'; /* Add leading 0 if we have no digits before the decimal point */
1516 /* Add any leading negative or currency sign */
1517 while (dwFmt & (CF_MINUS_LEFT|CF_CY_LEFT))
1519 switch (dwFmt & (CF_MINUS_LEFT|CF_MINUS_BEFORE|CF_CY_LEFT))
1521 case CF_MINUS_LEFT:
1522 case CF_MINUS_LEFT|CF_CY_LEFT:
1523 while (lpszNeg >= lpszNegStart)
1524 *szOut-- = *lpszNeg--;
1525 dwFmt &= ~CF_MINUS_LEFT;
1526 break;
1528 case CF_CY_LEFT:
1529 case CF_CY_LEFT|CF_MINUS_BEFORE:
1530 case CF_MINUS_LEFT|CF_MINUS_BEFORE|CF_CY_LEFT:
1531 if (dwFmt & CF_CY_SPACE)
1532 *szOut-- = ' ';
1533 while (lpszCy >= lpszCyStart)
1534 *szOut-- = *lpszCy--;
1535 dwFmt &= ~(CF_CY_LEFT|CF_MINUS_BEFORE);
1536 break;
1539 if (dwFmt & CF_PARENS)
1540 *szOut-- = '(';
1541 szOut++;
1543 iRet = lstrlenW(szOut) + 1;
1544 if (cchOut)
1546 if (iRet <= cchOut)
1547 memcpy(lpCurrencyStr, szOut, iRet * sizeof(WCHAR));
1548 else
1550 memcpy(lpCurrencyStr, szOut, cchOut * sizeof(WCHAR));
1551 lpCurrencyStr[cchOut - 1] = '\0';
1552 SetLastError(ERROR_INSUFFICIENT_BUFFER);
1553 iRet = 0;
1556 return iRet;
1558 error:
1559 SetLastError(lpFormat && dwFlags ? ERROR_INVALID_FLAGS : ERROR_INVALID_PARAMETER);
1560 return 0;
1563 /***********************************************************************
1564 * GetCurrencyFormatEx (KERNEL32.@)
1566 int WINAPI GetCurrencyFormatEx(LPCWSTR localename, DWORD flags, LPCWSTR value,
1567 const CURRENCYFMTW *format, LPWSTR str, int len)
1569 TRACE("(%s,0x%08lx,%s,%p,%p,%d)\n", debugstr_w(localename), flags,
1570 debugstr_w(value), format, str, len);
1572 return GetCurrencyFormatW( LocaleNameToLCID(localename, 0), flags, value, format, str, len);