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;
16  
17  import java.text.NumberFormat;
18  import java.util.IllformedLocaleException;
19  import java.util.Locale;
20  
21  import org.htmlunit.BrowserVersion;
22  import org.htmlunit.corejs.javascript.Context;
23  import org.htmlunit.corejs.javascript.Function;
24  import org.htmlunit.corejs.javascript.Scriptable;
25  import org.htmlunit.javascript.JavaScriptEngine;
26  
27  /**
28   * Contains some missing features of Rhino NativeNumber.
29   *
30   * @author Ahmed Ashour
31   * @author Ronald Brill
32   */
33  public final class NumberCustom {
34  
35      private NumberCustom() {
36          super();
37      }
38  
39      /**
40       * Returns a string with a language sensitive representation of this number.
41       * @param context the JavaScript context
42       * @param scope the scope
43       * @param thisObj the scriptable
44       * @param args the arguments passed into the method
45       * @param function the function
46       * @return the string
47       */
48      public static String toLocaleString(final Context context, final Scriptable scope,
49              final Scriptable thisObj, final Object[] args, final Function function) {
50          if (args.length != 0 && args[0] instanceof String) {
51              final String localeStr = (String) args[0];
52              try {
53                  final Locale locale = new Locale.Builder().setLanguageTag(localeStr).build();
54                  return NumberFormat.getInstance(locale).format(Double.parseDouble(thisObj.toString()));
55              }
56              catch (final IllformedLocaleException e) {
57                  throw JavaScriptEngine.rangeError("Invalid language tag: " + localeStr);
58              }
59          }
60  
61          final BrowserVersion browserVersion = ((Window) thisObj.getParentScope()).getBrowserVersion();
62          final Locale locale = Locale.forLanguageTag(browserVersion.getBrowserLanguage());
63          return NumberFormat.getInstance(locale).format(Double.parseDouble(thisObj.toString()));
64      }
65  }