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