View Javadoc
1   /*
2    * Copyright (c) 2002-2025 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.javascript.HtmlUnitScriptable;
31  import org.htmlunit.javascript.JavaScriptEngine;
32  import org.htmlunit.javascript.configuration.JsxClass;
33  import org.htmlunit.javascript.configuration.JsxConstructor;
34  import org.htmlunit.javascript.configuration.JsxFunction;
35  import org.htmlunit.javascript.host.Window;
36  import org.htmlunit.util.StringUtils;
37  
38  /**
39   * A JavaScript object for {@code NumberFormat}.
40   *
41   * @author Ahmed Ashour
42   * @author Ronald Brill
43   */
44  @JsxClass
45  public class NumberFormat extends HtmlUnitScriptable {
46  
47      private static final ConcurrentHashMap<String, String> CHROME_FORMATS_ = new ConcurrentHashMap<>();
48      private static final ConcurrentHashMap<String, String> EDGE_FORMATS_ = new ConcurrentHashMap<>();
49      private static final ConcurrentHashMap<String, String> FF_FORMATS_ = new ConcurrentHashMap<>();
50      private static final ConcurrentHashMap<String, String> FF_ESR_FORMATS_ = new ConcurrentHashMap<>();
51  
52      private transient NumberFormatHelper formatter_;
53  
54      static {
55          final Map<String, String> commonFormats = new HashMap<>();
56          commonFormats.put("", "");
57          commonFormats.put("ar-DZ", ".,");
58          commonFormats.put("ar-LY", ".,");
59          commonFormats.put("ar-MA", ".,");
60          commonFormats.put("ar-TN", ".,");
61          commonFormats.put("id", ".,");
62          commonFormats.put("de-AT", "\u00a0");
63          commonFormats.put("de-CH", "\u2019");
64          commonFormats.put("en-ZA", "\u00a0,");
65          commonFormats.put("es-CR", "\u00a0,");
66          commonFormats.put("fr-LU", ".,");
67          commonFormats.put("hi-IN", ",.0");
68          commonFormats.put("it-CH", "\u2019");
69          commonFormats.put("pt-PT", "\u00a0,");
70          commonFormats.put("sq", "\u00a0,");
71  
72          commonFormats.put("ar-AE", ",.0");
73          commonFormats.put("fr", "\u202f,");
74          commonFormats.put("fr-CA", "\u00a0,");
75  
76          commonFormats.put("ar", ",.0");
77          commonFormats.put("ar-BH", "\u066c\u066b\u0660");
78          commonFormats.put("ar-EG", "\u066c\u066b\u0660");
79          commonFormats.put("ar-IQ", "\u066c\u066b\u0660");
80          commonFormats.put("ar-JO", "\u066c\u066b\u0660");
81          commonFormats.put("ar-KW", "\u066c\u066b\u0660");
82          commonFormats.put("ar-LB", "\u066c\u066b\u0660");
83          commonFormats.put("ar-OM", "\u066c\u066b\u0660");
84          commonFormats.put("ar-QA", "\u066c\u066b\u0660");
85          commonFormats.put("ar-SA", "\u066c\u066b\u0660");
86          commonFormats.put("ar-SD", "\u066c\u066b\u0660");
87          commonFormats.put("ar-SY", "\u066c\u066b\u0660");
88          commonFormats.put("ar-YE", "\u066c\u066b\u0660");
89  
90          FF_FORMATS_.putAll(commonFormats);
91          FF_ESR_FORMATS_.putAll(commonFormats);
92  
93          commonFormats.put("be", ",.");
94          commonFormats.put("mk", ",.");
95          commonFormats.put("is", ",.");
96  
97          CHROME_FORMATS_.putAll(commonFormats);
98          CHROME_FORMATS_.put("sq", ",.");
99  
100         EDGE_FORMATS_.putAll(commonFormats);
101     }
102 
103     /**
104      * Default constructor.
105      */
106     public NumberFormat() {
107         super();
108     }
109 
110     private NumberFormat(final String[] locales, final BrowserVersion browserVersion) {
111         super();
112 
113         final Map<String, String> formats;
114         if (browserVersion.isChrome()) {
115             formats = CHROME_FORMATS_;
116         }
117         else if (browserVersion.isEdge()) {
118             formats = EDGE_FORMATS_;
119         }
120         else if (browserVersion.isFirefoxESR()) {
121             formats = FF_ESR_FORMATS_;
122         }
123         else {
124             formats = FF_FORMATS_;
125         }
126 
127         String locale = "";
128         String pattern = null;
129 
130         for (final String l : locales) {
131             pattern = getPattern(formats, l);
132             if (pattern != null) {
133                 locale = l;
134             }
135         }
136 
137         if (pattern == null) {
138             pattern = formats.get("");
139             if (locales.length > 0) {
140                 locale = locales[0];
141             }
142         }
143 
144         formatter_ = new NumberFormatHelper(locale, browserVersion, pattern);
145     }
146 
147     private static String getPattern(final Map<String, String> formats, final String locale) {
148         if ("no-NO-NY".equals(locale)) {
149             throw JavaScriptEngine.rangeError("Invalid language tag: " + locale);
150         }
151         String pattern = formats.get(locale);
152         if (pattern == null && locale.indexOf('-') != -1) {
153             pattern = formats.get(locale.substring(0, locale.indexOf('-')));
154         }
155         return pattern;
156     }
157 
158     /**
159      * JavaScript constructor.
160      * @param cx the current context
161      * @param scope the scope
162      * @param args the arguments to the WebSocket constructor
163      * @param ctorObj the function object
164      * @param inNewExpr Is new or not
165      * @return the java object to allow JavaScript to access
166      */
167     @JsxConstructor
168     public static Scriptable jsConstructor(final Context cx, final Scriptable scope,
169             final Object[] args, final Function ctorObj, final boolean inNewExpr) {
170         final String[] locales;
171         if (args.length == 0) {
172             locales = new String[] {""};
173         }
174         else {
175             if (args[0] instanceof NativeArray) {
176                 final NativeArray array = (NativeArray) args[0];
177                 locales = new String[(int) array.getLength()];
178                 for (int i = 0; i < locales.length; i++) {
179                     locales[i] = JavaScriptEngine.toString(array.get(i));
180                 }
181             }
182             else {
183                 locales = new String[] {JavaScriptEngine.toString(args[0])};
184             }
185         }
186         final Window window = getWindow(ctorObj);
187         final NumberFormat format = new NumberFormat(locales, window.getBrowserVersion());
188         format.setParentScope(window);
189         format.setPrototype(((FunctionObject) ctorObj).getClassPrototype());
190         return format;
191     }
192 
193     /**
194      * Formats a number according to the locale and formatting options of this Intl.NumberFormat object.
195      * @param object the JavaScript object to convert
196      * @return the dated formated
197      */
198     @JsxFunction
199     public String format(final Object object) {
200         final double number = JavaScriptEngine.toNumber(object);
201         return formatter_.format(number);
202     }
203 
204     /**
205      * @return A new object with properties reflecting the locale and date and time formatting options
206      *         computed during the initialization of the given {@code DateTimeFormat} object.
207      */
208     @JsxFunction
209     public Scriptable resolvedOptions() {
210         return Context.getCurrentContext().newObject(getParentScope());
211     }
212 
213     /**
214      * Helper.
215      */
216     static final class NumberFormatHelper {
217         private final DecimalFormat formatter_;
218 
219         NumberFormatHelper(final String localeName, final BrowserVersion browserVersion, final String pattern) {
220             Locale locale = browserVersion.getBrowserLocale();
221             if (!StringUtils.isEmptyOrNull(localeName)) {
222                 locale = Locale.forLanguageTag(localeName);
223             }
224 
225             final DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale);
226 
227             if (pattern.length() > 0) {
228                 final char groupingSeparator = pattern.charAt(0);
229                 if (groupingSeparator != ' ') {
230                     symbols.setGroupingSeparator(groupingSeparator);
231                 }
232 
233                 if (pattern.length() > 1) {
234                     final char decimalSeparator = pattern.charAt(1);
235                     if (decimalSeparator != ' ') {
236                         symbols.setDecimalSeparator(decimalSeparator);
237                     }
238 
239                     if (pattern.length() > 2) {
240                         final char zeroDigit = pattern.charAt(2);
241                         if (zeroDigit != ' ') {
242                             symbols.setZeroDigit(zeroDigit);
243                         }
244                     }
245                 }
246             }
247 
248             formatter_ = new DecimalFormat("#,##0.###", symbols);
249         }
250 
251         String format(final double number) {
252             return formatter_.format(number);
253         }
254     }
255 }