View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.javascript.host.intl;
16  
17  import java.text.DecimalFormat;
18  import java.text.DecimalFormatSymbols;
19  import java.util.HashMap;
20  import java.util.Locale;
21  import java.util.Map;
22  import java.util.concurrent.ConcurrentHashMap;
23  
24  import org.htmlunit.BrowserVersion;
25  import org.htmlunit.corejs.javascript.Context;
26  import org.htmlunit.corejs.javascript.Function;
27  import org.htmlunit.corejs.javascript.FunctionObject;
28  import org.htmlunit.corejs.javascript.NativeArray;
29  import org.htmlunit.corejs.javascript.Scriptable;
30  import org.htmlunit.corejs.javascript.VarScope;
31  import org.htmlunit.javascript.HtmlUnitScriptable;
32  import org.htmlunit.javascript.JavaScriptEngine;
33  import org.htmlunit.javascript.configuration.JsxClass;
34  import org.htmlunit.javascript.configuration.JsxConstructor;
35  import org.htmlunit.javascript.configuration.JsxFunction;
36  import org.htmlunit.javascript.configuration.JsxStaticFunction;
37  import org.htmlunit.javascript.configuration.JsxSymbolConstant;
38  import org.htmlunit.javascript.host.Window;
39  import org.htmlunit.util.StringUtils;
40  
41  /**
42   * A JavaScript object for Intl.NumberFormat.
43   *
44   * @author Ahmed Ashour
45   * @author Ronald Brill
46   * @author Lai Quang Duong
47   *
48   * @see <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat">MDN Documentation</a>
49   */
50  @JsxClass
51  public class NumberFormat extends HtmlUnitScriptable {
52  
53      /** Symbol.toStringTag support. */
54      @JsxSymbolConstant
55      public static final String TO_STRING_TAG = "Intl.NumberFormat";
56  
57      private static final ConcurrentHashMap<String, String> CHROME_FORMATS_ = new ConcurrentHashMap<>();
58      private static final ConcurrentHashMap<String, String> EDGE_FORMATS_ = new ConcurrentHashMap<>();
59      private static final ConcurrentHashMap<String, String> FF_FORMATS_ = new ConcurrentHashMap<>();
60      private static final ConcurrentHashMap<String, String> FF_ESR_FORMATS_ = new ConcurrentHashMap<>();
61  
62      private transient NumberFormatHelper formatter_;
63  
64      static {
65          final Map<String, String> commonFormats = new HashMap<>();
66          commonFormats.put("", "");
67          commonFormats.put("ar-DZ", ".,");
68          commonFormats.put("ar-LY", ".,");
69          commonFormats.put("ar-MA", ".,");
70          commonFormats.put("ar-TN", ".,");
71          commonFormats.put("id", ".,");
72          commonFormats.put("de-AT", "\u00a0");
73          commonFormats.put("de-CH", "'");
74          commonFormats.put("en-ZA", "\u00a0,");
75          commonFormats.put("es-CR", "\u00a0,");
76          commonFormats.put("fr-LU", ".,");
77          commonFormats.put("hi-IN", ",.0");
78          commonFormats.put("it-CH", "'");
79          commonFormats.put("pt-PT", "\u00a0,");
80          commonFormats.put("sq", "\u00a0,");
81  
82          commonFormats.put("ar-AE", ",.0");
83          commonFormats.put("fr", "\u202f,");
84          commonFormats.put("fr-CA", "\u00a0,");
85  
86          commonFormats.put("ar", ",.0");
87          commonFormats.put("ar-BH", "\u066c\u066b\u0660");
88          commonFormats.put("ar-EG", "\u066c\u066b\u0660");
89          commonFormats.put("ar-IQ", "\u066c\u066b\u0660");
90          commonFormats.put("ar-JO", "\u066c\u066b\u0660");
91          commonFormats.put("ar-KW", "\u066c\u066b\u0660");
92          commonFormats.put("ar-LB", "\u066c\u066b\u0660");
93          commonFormats.put("ar-OM", "\u066c\u066b\u0660");
94          commonFormats.put("ar-QA", "\u066c\u066b\u0660");
95          commonFormats.put("ar-SA", "\u066c\u066b\u0660");
96          commonFormats.put("ar-SD", "\u066c\u066b\u0660");
97          commonFormats.put("ar-SY", "\u066c\u066b\u0660");
98          commonFormats.put("ar-YE", "\u066c\u066b\u0660");
99  
100         FF_FORMATS_.putAll(commonFormats);
101         FF_FORMATS_.put("fr-CH", "',");
102 
103         FF_ESR_FORMATS_.putAll(commonFormats);
104         FF_ESR_FORMATS_.put("fr-CH", "',");
105 
106         commonFormats.put("be", ",.");
107         commonFormats.put("mk", ",.");
108         commonFormats.put("is", ",.");
109 
110         CHROME_FORMATS_.putAll(commonFormats);
111         CHROME_FORMATS_.put("sq", ",.");
112 
113         EDGE_FORMATS_.putAll(commonFormats);
114     }
115 
116     /**
117      * Default constructor.
118      */
119     public NumberFormat() {
120         super();
121     }
122 
123     private NumberFormat(final String[] locales, final BrowserVersion browserVersion) {
124         super();
125 
126         final Map<String, String> formats;
127         if (browserVersion.isChrome()) {
128             formats = CHROME_FORMATS_;
129         }
130         else if (browserVersion.isEdge()) {
131             formats = EDGE_FORMATS_;
132         }
133         else if (browserVersion.isFirefoxESR()) {
134             formats = FF_ESR_FORMATS_;
135         }
136         else {
137             formats = FF_FORMATS_;
138         }
139 
140         String locale = "";
141         String pattern = null;
142 
143         for (final String l : locales) {
144             pattern = getPattern(formats, l);
145             if (pattern != null) {
146                 locale = l;
147             }
148         }
149 
150         if (pattern == null) {
151             pattern = formats.get("");
152             if (locales.length > 0) {
153                 locale = locales[0];
154             }
155         }
156 
157         formatter_ = new NumberFormatHelper(locale, browserVersion, pattern);
158     }
159 
160     private static String getPattern(final Map<String, String> formats, final String locale) {
161         if ("no-NO-NY".equals(locale)) {
162             throw JavaScriptEngine.rangeError("Invalid language tag: " + locale);
163         }
164         String pattern = formats.get(locale);
165         if (pattern == null && locale.indexOf('-') != -1) {
166             pattern = formats.get(locale.substring(0, locale.indexOf('-')));
167         }
168         return pattern;
169     }
170 
171     /**
172      * JavaScript constructor.
173      * @param cx the current context
174      * @param scope the scope
175      * @param args the arguments to the NumberFormat constructor
176      * @param ctorObj the function object
177      * @param inNewExpr {@code true} if invoked with the {@code new} operator
178      * @return the Java object that JavaScript can access
179      */
180     @JsxConstructor
181     public static Scriptable jsConstructor(final Context cx, final VarScope scope,
182             final Object[] args, final Function ctorObj, final boolean inNewExpr) {
183         final String[] locales;
184         if (args.length == 0) {
185             locales = new String[] {""};
186         }
187         else {
188             if (args[0] instanceof NativeArray array) {
189                 locales = new String[(int) array.getLength()];
190                 for (int i = 0; i < locales.length; i++) {
191                     locales[i] = JavaScriptEngine.toString(array.get(i));
192                 }
193             }
194             else {
195                 locales = new String[] {JavaScriptEngine.toString(args[0])};
196             }
197         }
198         final Window window = getWindow(ctorObj);
199         final NumberFormat format = new NumberFormat(locales, window.getBrowserVersion());
200         format.setParentScope(getTopLevelScope(scope));
201         format.setPrototype(((FunctionObject) ctorObj).getClassPrototype());
202         return format;
203     }
204 
205     /**
206      * Formats a number according to the locale and formatting options of this Intl.NumberFormat object.
207      * @param object the JavaScript object to convert
208      * @return the formatted number
209      */
210     @JsxFunction
211     public String format(final Object object) {
212         final double number = JavaScriptEngine.toNumber(object);
213         return formatter_.format(number);
214     }
215 
216     /**
217      * Returns the resolved options for this Intl.NumberFormat object.
218      * @return a new object with properties reflecting the locale and number formatting options
219      *         computed during the initialization of the given {@code NumberFormat} object.
220      */
221     @JsxFunction
222     public Scriptable resolvedOptions() {
223         return JavaScriptEngine.newObject(getParentScope());
224     }
225 
226     /**
227      * Returns an array containing those of the provided locales that are supported
228      * without having to fall back to the default locale.
229      * @param localesArgument A string with a BCP 47 language tag, or an array of such strings
230      * @param options unused
231      * @return an array containing supported locales
232      */
233     @JsxStaticFunction
234     public static Scriptable supportedLocalesOf(final Scriptable localesArgument, final Scriptable options) {
235         return Intl.supportedLocalesOf(localesArgument);
236     }
237 
238     @Override
239     public Object getDefaultValue(final Class<?> hint) {
240         if (String.class.equals(hint) || hint == null) {
241             return "[object Intl.NumberFormat]";
242         }
243         return super.getDefaultValue(hint);
244     }
245 
246     /**
247      * Helper.
248      */
249     static final class NumberFormatHelper {
250         private final DecimalFormat formatter_;
251 
252         NumberFormatHelper(final String localeName, final BrowserVersion browserVersion, final String pattern) {
253             Locale locale = browserVersion.getBrowserLocale();
254             if (!StringUtils.isEmptyOrNull(localeName)) {
255                 locale = Locale.forLanguageTag(localeName);
256             }
257 
258             final DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale);
259 
260             if (pattern.length() > 0) {
261                 final char groupingSeparator = pattern.charAt(0);
262                 if (groupingSeparator != ' ') {
263                     symbols.setGroupingSeparator(groupingSeparator);
264                 }
265 
266                 if (pattern.length() > 1) {
267                     final char decimalSeparator = pattern.charAt(1);
268                     if (decimalSeparator != ' ') {
269                         symbols.setDecimalSeparator(decimalSeparator);
270                     }
271 
272                     if (pattern.length() > 2) {
273                         final char zeroDigit = pattern.charAt(2);
274                         if (zeroDigit != ' ') {
275                             symbols.setZeroDigit(zeroDigit);
276                         }
277                     }
278                 }
279             }
280 
281             formatter_ = new DecimalFormat("#,##0.###", symbols);
282         }
283 
284         String format(final double number) {
285             return formatter_.format(number);
286         }
287     }
288 }