使用浏览器,我如何知道客户端使用哪个小数分隔符?

时间:2022-04-15 07:25:19

I'm developing a web application.

我正在开发一个Web应用程序。

I need to display some decimal data correctly so that it can be copied and pasted into a certain GUI application that is not under my control.

我需要正确显示一些十进制数据,以便可以将其复制并粘贴到不受我控制的某个GUI应用程序中。

The GUI application is locale sensitive and it accepts only the correct decimal separator which is set in the system.

GUI应用程序是区域设置敏感的,它只接受在系统中设置的正确的小数分隔符。

I can guess the decimal separator from Accept-Language and the guess will be correct in 95% cases, but sometimes it fails.

我可以猜测Accept-Language中的小数分隔符,并且在95%的情况下猜测是正确的,但有时它会失败。

Is there any way to do it on server side (preferably, so that I can collect statistics), or on client side?

有没有办法在服务器端(最好是我可以收集统计信息),或在客户端?

Update:

更新:

The whole point of the task is doing it automatically.

任务的重点是自动完成。

In fact, this webapp is a kind of online interface to a legacy GUI which helps to fill the forms correctly.

事实上,这个webapp是一种传统GUI的在线界面,有助于正确填写表单。

The kind of users that use it mostly have no idea on what a decimal separator is.

使用它的用户大多不知道小数分隔符是什么。

The Accept-Language solution is implemented and works, but I'd like to improve it.

Accept-Language解决方案已实施并正常运行,但我想改进它。

Update2:

UPDATE2:

I need to retrive a very specific setting: decimal separator set in Control Panel / Regional and Language Options / Regional Options / Customize.

我需要检索一个非常具体的设置:在控制面板/区域和语言选项/区域选项/自定义中设置小数分隔符。

I deal with four kinds of operating systems:

我处理四种操作系统:

  1. Russian Windows with a comma as a DS (80%).
  2. 俄语Windows用逗号作为DS(80%)。
  3. English Windows with a period as a DS (15%).
  4. 英文版Windows,期间为DS(15%)。
  5. Russian Windows with a period as a DS to make poorly written English applications work (4%).
  6. 俄罗斯Windows有一段时间作为DS,使写得不好的英文应用程序工作(4%)。
  7. English Windows with a comma as a DS to make poorly written Russian applications work (1%).
  8. 使用逗号作为DS的英文Windows可以使写得不好的俄语应用程序正常工作(1%)。

All 100% of clients are in Russia and the legacy application deals with Russian goverment-issued forms, so asking for a country will yield 100% of Russian Federation, and GeoIP will yield 80% of Russian Federation and 20% of other (incorrect) answers.

所有100%的客户都在俄罗斯,遗留申请涉及俄罗斯*签发的表格,因此要求一个国家将收取100%的俄罗斯联邦,GeoIP将收益80%的俄罗斯联邦和20%的其他(不正确)答案。

11 个解决方案

#1


100  

Here is a simple JavaScript function that will return this information. Tested in Firefox, IE6, and IE7. I had to close and restart my browser in between every change to the setting under Control Panel / Regional and Language Options / Regional Options / Customize. However, it picked up not only the comma and period, but also oddball custom things, like the letter "a".

这是一个简单的JavaScript函数,它将返回此信息。在Firefox,IE6和IE7中测试过。我必须在每次更改控制面板/区域和语言选项/区域选项/自定义下的设置之间关闭并重新启动浏览器。然而,它不仅包括逗号和句号,还包括古怪的自定义内容,如字母“a”。

function whatDecimalSeparator() {
    var n = 1.1;
    n = n.toLocaleString().substring(1, 2);
    return n;
}

function whatDecimalSeparator() {
    var n = 1.1;
    n = n.toLocaleString().substring(1, 2);
    return n;
}

console.log('You use "' + whatDecimalSeparator() + '" as Decimal seprator');

Does this help?

这有帮助吗?

#2


8  

Ask the user, do not guess. Have a setting for it in your web application.

询问用户,不要猜。在您的Web应用程序中设置它。

Edited to add:

编辑添加:

I think it is ok to guess the default setting that works ok, say, 95% of the time. What I meant was that the user should still be able to override whatever guesses the software made. I've been frustrated too many times already when a software tries to be too smart and does not allow to be corrected.

我认为可以猜测默认设置是否正常,比如95%的时间。我的意思是用户仍然可以覆盖软件所做的任何猜测。当软件试图过于聪明并且不允许纠正时,我已经沮丧太多次了。

#3


7  

function getDecimalSeparator() {
    //fallback  
       var decSep = ".";

        try {
            // this works in FF, Chrome, IE, Safari and Opera
            var sep = parseFloat(3/2).toLocaleString().substring(1,2);
            if (sep === '.' || sep === ',') {
                decSep = sep;
            }
        } catch(e){}

        return decSep;
    }

#4


5  

I can guess the decimal separator from Accept-Language and the guess will be correct in 95% cases, but sometimes it fails.

我可以猜测Accept-Language中的小数分隔符,并且在95%的情况下猜测是正确的,但有时它会失败。

This is IMO the best course of action. In order to handle the failures, add a link to set it manually next to the display area.

这是IMO最好的行动方案。为了处理故障,请添加一个链接以在显示区域旁边手动设置。

#5


5  

Why not

为什么不

0.1.toLocaleString().replace(/\d/g, '')

#6


2  

OK, I have something to show, more a proof of concept than a finished product, but because of lack of precise specifications, I leave it this way (or I will over-engineer it). I post in a separate message because it will be a bit long. I took the opportunity to try a bit more jQuery...

好吧,我有东西要展示,更多的是概念证明,而不是成品,但由于缺乏精确的规格,我就这样离开(或者我会过度设计它)。我发布了一个单独的消息,因为它会有点长。我借此机会尝试了更多jQuery ......

The Java code: GetLocaleInfo.java

Java代码:GetLocaleInfo.java

import java.applet.*;
import java.util.Locale;
import java.text.*;

public class GetLocaleInfo extends Applet
{
  Locale loc;
  NumberFormat nf;
  NumberFormat cnf;
  NumberFormat pnf;

  // For running as plain application
  public static void main(String args[])
  {
    final Applet applet = new GetLocaleInfo();
    applet.init();
    applet.start();
  }

  public void init() // Applet is loaded
  {
    // Use current locale
    loc = Locale.getDefault();
    nf = NumberFormat.getInstance();
    cnf = NumberFormat.getCurrencyInstance();
    pnf = NumberFormat.getPercentInstance();
  }

  public void start() // Applet should start
  {
    // Following output goes to Java console
    System.out.println(GetLocaleInformation());
    System.out.println(nf.format(0.1));
    System.out.println(cnf.format(1.0));
    System.out.println(pnf.format(0.01));
  }

  public String GetLocaleInformation()
  {
    return String.format("Locale for %s: country=%s (%s / %s), lang=%s (%s / %s), variant=%s (%s)",
        loc.getDisplayName(),
        loc.getDisplayCountry(),
        loc.getCountry(),
        loc.getISO3Country(),

        loc.getDisplayLanguage(),
        loc.getLanguage(),
        loc.getISO3Language(),

        loc.getDisplayVariant(),
        loc.getVariant()
    );
  }

  public String FormatNumber(String number)
  {
    double value = 0;
    try
    {
      value = Double.parseDouble(number);
    }
    catch (NumberFormatException nfe)
    {
      return "!";
    }
    return nf.format(value);
  }

  public String FormatCurrency(String number)
  {
    double value = 0;
    try
    {
      value = Double.parseDouble(number);
    }
    catch (NumberFormatException nfe)
    {
      return "!";
    }
    return cnf.format(value);
  }

  public String FormatPercent(String number)
  {
    double value = 0;
    try
    {
      value = Double.parseDouble(number);
    }
    catch (NumberFormatException nfe)
    {
      return "!";
    }
    return pnf.format(value);
  }
}

An example of HTML page using the above applet: GetLocaleInfo.html

使用上述applet的HTML页面示例:GetLocaleInfo.html

<!-- Header skipped for brevity -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"></script>
<script type="text/javascript">
var applet;
$(document).ready(function()
{
  applet = document.getElementById('LocaleInfo');
  $('#Results').text(applet.GetLocaleInformation());
});
</script>
<script type="text/javascript">
function DoFormatting()
{
  $('table.toFormat').each(function()
  {
    var table = $(this);
    $('td', table).each(function(cellId)
    {
      var val = $(this);
      if (val.is('.number'))
      {
        val.text(applet.FormatNumber(val.text()));
      }
      else if (val.is('.currency'))
      {
        val.text(applet.FormatCurrency(val.text()));
      }
      else if (val.is('.percent'))
      {
        val.text(applet.FormatPercent(val.text()));
      }
    });
  });
}
</script>
</head>
<body>
  <div id="Container">
    <p>Page to demonstrate how JavaScript can get locale information from Java</p>
    <div id="AppletContainer">
      <object classid="java:GetLocaleInfo.class"
          type="application/x-java-applet" codetype="application/java"
          name="LocaleInfo" id="LocaleInfo" width="0" height="0">
        <param name="code" value="GetLocaleInfo"/>
        <param name="mayscript" value="true"/>
        <param name="scriptable" value="true"/>
        <p><!-- Displayed if object isn't supported -->
          <strong>This browser does not have Java enabled.</strong>
          <br>
          <a href="http://java.sun.com/products/plugin/downloads/index.html" title="Download Java plug-in">
          Get the latest Java plug-in here
          </a> (or enable Java support).
        </p>
      </object>
    </div><!-- AppletContainer -->
    <p>
    Click on the button to format the table content to the locale rules of the user.
    </p>
    <input type="button" name="DoFormatting" id="DoFormatting" value="Format the table" onclick="javascript:DoFormatting()"/>
    <div id="Results">
    </div><!-- Results -->
<table class="toFormat">
<caption>Synthetic View</caption>
<thead><tr>
<th>Name</th><th>Value</th><th>Cost</th><th>Discount</th>
</tr></thead>
<tbody>
<tr><td>Foo</td><td class="number">3.1415926</td><td class="currency">21.36</td><td class="percent">0.196</td></tr>
<tr><td>Bar</td><td class="number">159263.14</td><td class="currency">33</td><td class="percent">0.33</td></tr>
<tr><td>Baz</td><td class="number">15926</td><td class="currency">12.99</td><td class="percent">0.05</td></tr>
<tr><td>Doh</td><td class="number">0.01415926</td><td class="currency">5.1</td><td class="percent">0.1</td></tr>
</tbody>
</table>
  </div><!-- Container -->
</body>
</html>

Tested on Firefox 3.0, IE 6, Safari 3.1 and Opera 9.50, on Windows XP Pro SP3. It works without problem with the first two, on Safari I have a strange error after init() call:

在Windows XP Pro SP3上测试Firefox 3.0,IE 6,Safari 3.1和Opera 9.50。前两个工作没有问题,在Safari上我在init()调用后有一个奇怪的错误:

java.net.MalformedURLException: no protocol:
    at java.net.URL.<init>(Unknown Source)
    at java.net.URL.<init>(Unknown Source)
    at java.net.URL.<init>(Unknown Source)
    at sun.plugin.liveconnect.SecureInvocation.checkLiveConnectCaller(Unknown Source)
    at sun.plugin.liveconnect.SecureInvocation.access$000(Unknown Source)
    at sun.plugin.liveconnect.SecureInvocation$2.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.plugin.liveconnect.SecureInvocation.CallMethod(Unknown Source)

but it still works.

但它仍然有效。

I can't get it work with Opera: the applet loads correctly, as I can see the trace of init() call in the Java console, I have no errors when JavaScript calls the Java functions (except if I add and call a method getting a JSObject parameter, curiously), but the Java functions are not called (I added trace of the calls).
I believe Liveconnect works in Opera, but I don't see yet how. I will research a bit more.
[Update] I removed references to non-existing jar file (which doesn't stop other browsers) and I got a trace of the calls, but it doesn't update the page.
Mmm, if I do alert(applet.GetLocaleInformation()); I got the information, so it might be a jQuery issue.

我无法使用Opera:applet正确加载,因为我可以在Java控制台中看到init()调用的跟踪,当JavaScript调用Java函数时我没有错误(除非我添加并调用方法)奇怪地得到一个JSObject参数,但没有调用Java函数(我添加了调用的跟踪)。我相信Liveconnect可以在Opera中运行,但我还没有看到。我会再研究一下。 [更新]我删除了对不存在的jar文件的引用(它不会阻止其他浏览器),我得到了一些调用,但它没有更新页面。嗯,如果我做警报(applet.GetLocaleInformation());我得到了信息,所以它可能是一个jQuery问题。

#7


1  

I think you have to rely on JavaScript to give you the locale settings.
But apparently JS doesn't have direct access to this information.
I see Dojo Toolkit relies on an external database to find the locale information, although it might not take in account setting changes, for example.
Another workaround I see is to have a small silent Java applet that query this information from the system, and JavaScript to get it out of Java.
I can give more information if you don't know how to do it (if you want to go this convoluted route, of course).

我认为你必须依靠JavaScript来为你提供语言环境设置。但显然JS没有直接访问这些信息。我看到Dojo Toolkit依赖于外部数据库来查找区域设置信息,例如,它可能不会考虑设置更改。我看到的另一个解决方法是使用一个小的静态Java小程序从系统中查询此信息,并使用JavaScript从Java中获取它。如果你不知道怎么做,我可以提供更多的信息(当然,如果你想走这条错综复杂的路线)。

[EDIT] So I updated my knowledge of localization support in Java...
Unlike what I thought originally, you won't have directly the decimal separator or thousand separator characters directly, like you would do with line separator or path separator: instead Java offers APIs to format the numbers or dates you provide.
Somehow, it makes sense: in Europe you often put the currency symbol after the number, some countries (India?) have a more complex rule to separate digits, etc.

[编辑]所以我更新了我在Java中的本地化支持的知识...与我原来的想法不同,你不会直接使用小数分隔符或千位分隔符,就像你使用行分隔符或路径分隔符一样:而不是Java提供API来格式化您提供的数字或日期。不知何故,它有道理:在欧洲,你经常把货币符号放在数字后面,有些国家(印度?)有一个更复杂的规则来分隔数字等。

Another thing: Java correctly finds the current locale from the system, but doesn't take information from there (perhaps for above reasons). Instead it uses its own set of rules. So if you have a Spanish locale where you replaced decimal separator with an exclamation sign, Java won't use it (but perhaps neither your application, anyway...).

另一件事:Java正确地从系统中找到当前的语言环境,但不从那里获取信息(可能由于上述原因)。相反,它使用自己的一套规则。因此,如果你有一个西班牙语语言环境,你用感叹号替换小数分隔符,Java将不会使用它(但也许你的应用程序,无论如何......)。

So I am writing an applet exposing a service (functions) to JavaScript, allowing to format numbers to the current locale. You can use it as such, using JavaScript to format numbers on the browser. Or you can just feed it with some sample number and extract the symbols from there, using them locally or feeding them back to the server.

所以我正在编写一个向JavaScript公开服务(函数)的applet,允许将数字格式化为当前语言环境。您可以这样使用它,使用JavaScript格式化浏览器上的数字。或者你可以用一些样本号来提供它并从那里提取符号,在本地使用它们或将它们反馈给服务器。

I finish and test my applet and post it there soon.

我完成并测试我的applet并很快将其发​​布到那里。

#8


1  

Even if you knew what locale this "GUI Application" is running under, you still have to figure out how it is getting the current locale, and how it is determining the decimal separator.

即使您知道这个“GUI应用程序”正在运行的区域设置,您仍然需要弄清楚它是如何获取当前区域设置的,以及它如何确定小数分隔符。

i don't know how it is done on a Mac, but on Windows applications are supposed to interrogte the user's preferences set via the Control Panel. It's quite possible this mystery applicaiton is ignoring those settings, and using their own internal setup instead.

我不知道它是如何在Mac上完成的,但在Windows应用程序上应该通过控制面板询问用户的首选项。这个神秘的应用程序很可能忽略了这些设置,而是使用自己的内部设置。

Or perhaps they're taking the current locale, and inferring the rest, rather than being told.

或许他们正在采用当前的语言环境,并推断其余的,而不是被告知。

Even then, in english, numbers are given in groups of 3 digits, with a comma separating the groups. i.e.:

即便如此,在英语中,数字以3位数组的形式给出,逗号分隔各组。即:

5,197,359,078

Unless the number was an integer that contains a phone number:

除非该数字是包含电话号码的整数:

519-735-9078

Unless of course the number was an integer that contains an account number:

除非数字是一个包含帐号的整数:

5197359078

In which case, you're back to hard-coded overridden logic.

在这种情况下,您将回到硬编码的重写逻辑。

Edit: Removed currency example, since currency has its own formatting rules.

编辑:删除货币示例,因为货币有自己的格式规则。

#9


0  

"Is there any way to do it on server side (preferably, so that I can collect statistics), or on client side?"

“有没有办法在服务器端(最好是我可以收集统计数据),或在客户端?”

No you can't. That GUI is looking at some user or machine specific settings. First, you probably do not know at what settings this UI is looking. Second, with a webapplication you will probably not be able to check these settings (clientside --> Javacsript).

不,你不能。该GUI正在查看某些用户或计算机特定设置。首先,您可能不知道此UI正在查看的设置。其次,使用Web应用程序,您可能无法检查这些设置(clientside - > Javacsript)。

#10


0  

Using other people answers I compiled the following decimal and thousand separators utility functions:

使用其他人的答案我编译了以下十进制和千位分隔符实用程序函数:

var decimalSeparator = function() {
    return (1.1).toLocaleString().substring(1, 2);
};
var thousandSeparator = function() {
    return (1000).toLocaleString().substring(1, 2);
};

Enjoy!

请享用!

#11


-3  

Another possible solution: You could use something like GeoIP (example in PHP) to determine the user's location and decide based on these information.

另一种可能的解决方案:您可以使用GeoIP(PHP中的示例)来确定用户的位置,并根据这些信息做出决定。

#1


100  

Here is a simple JavaScript function that will return this information. Tested in Firefox, IE6, and IE7. I had to close and restart my browser in between every change to the setting under Control Panel / Regional and Language Options / Regional Options / Customize. However, it picked up not only the comma and period, but also oddball custom things, like the letter "a".

这是一个简单的JavaScript函数,它将返回此信息。在Firefox,IE6和IE7中测试过。我必须在每次更改控制面板/区域和语言选项/区域选项/自定义下的设置之间关闭并重新启动浏览器。然而,它不仅包括逗号和句号,还包括古怪的自定义内容,如字母“a”。

function whatDecimalSeparator() {
    var n = 1.1;
    n = n.toLocaleString().substring(1, 2);
    return n;
}

function whatDecimalSeparator() {
    var n = 1.1;
    n = n.toLocaleString().substring(1, 2);
    return n;
}

console.log('You use "' + whatDecimalSeparator() + '" as Decimal seprator');

Does this help?

这有帮助吗?

#2


8  

Ask the user, do not guess. Have a setting for it in your web application.

询问用户,不要猜。在您的Web应用程序中设置它。

Edited to add:

编辑添加:

I think it is ok to guess the default setting that works ok, say, 95% of the time. What I meant was that the user should still be able to override whatever guesses the software made. I've been frustrated too many times already when a software tries to be too smart and does not allow to be corrected.

我认为可以猜测默认设置是否正常,比如95%的时间。我的意思是用户仍然可以覆盖软件所做的任何猜测。当软件试图过于聪明并且不允许纠正时,我已经沮丧太多次了。

#3


7  

function getDecimalSeparator() {
    //fallback  
       var decSep = ".";

        try {
            // this works in FF, Chrome, IE, Safari and Opera
            var sep = parseFloat(3/2).toLocaleString().substring(1,2);
            if (sep === '.' || sep === ',') {
                decSep = sep;
            }
        } catch(e){}

        return decSep;
    }

#4


5  

I can guess the decimal separator from Accept-Language and the guess will be correct in 95% cases, but sometimes it fails.

我可以猜测Accept-Language中的小数分隔符,并且在95%的情况下猜测是正确的,但有时它会失败。

This is IMO the best course of action. In order to handle the failures, add a link to set it manually next to the display area.

这是IMO最好的行动方案。为了处理故障,请添加一个链接以在显示区域旁边手动设置。

#5


5  

Why not

为什么不

0.1.toLocaleString().replace(/\d/g, '')

#6


2  

OK, I have something to show, more a proof of concept than a finished product, but because of lack of precise specifications, I leave it this way (or I will over-engineer it). I post in a separate message because it will be a bit long. I took the opportunity to try a bit more jQuery...

好吧,我有东西要展示,更多的是概念证明,而不是成品,但由于缺乏精确的规格,我就这样离开(或者我会过度设计它)。我发布了一个单独的消息,因为它会有点长。我借此机会尝试了更多jQuery ......

The Java code: GetLocaleInfo.java

Java代码:GetLocaleInfo.java

import java.applet.*;
import java.util.Locale;
import java.text.*;

public class GetLocaleInfo extends Applet
{
  Locale loc;
  NumberFormat nf;
  NumberFormat cnf;
  NumberFormat pnf;

  // For running as plain application
  public static void main(String args[])
  {
    final Applet applet = new GetLocaleInfo();
    applet.init();
    applet.start();
  }

  public void init() // Applet is loaded
  {
    // Use current locale
    loc = Locale.getDefault();
    nf = NumberFormat.getInstance();
    cnf = NumberFormat.getCurrencyInstance();
    pnf = NumberFormat.getPercentInstance();
  }

  public void start() // Applet should start
  {
    // Following output goes to Java console
    System.out.println(GetLocaleInformation());
    System.out.println(nf.format(0.1));
    System.out.println(cnf.format(1.0));
    System.out.println(pnf.format(0.01));
  }

  public String GetLocaleInformation()
  {
    return String.format("Locale for %s: country=%s (%s / %s), lang=%s (%s / %s), variant=%s (%s)",
        loc.getDisplayName(),
        loc.getDisplayCountry(),
        loc.getCountry(),
        loc.getISO3Country(),

        loc.getDisplayLanguage(),
        loc.getLanguage(),
        loc.getISO3Language(),

        loc.getDisplayVariant(),
        loc.getVariant()
    );
  }

  public String FormatNumber(String number)
  {
    double value = 0;
    try
    {
      value = Double.parseDouble(number);
    }
    catch (NumberFormatException nfe)
    {
      return "!";
    }
    return nf.format(value);
  }

  public String FormatCurrency(String number)
  {
    double value = 0;
    try
    {
      value = Double.parseDouble(number);
    }
    catch (NumberFormatException nfe)
    {
      return "!";
    }
    return cnf.format(value);
  }

  public String FormatPercent(String number)
  {
    double value = 0;
    try
    {
      value = Double.parseDouble(number);
    }
    catch (NumberFormatException nfe)
    {
      return "!";
    }
    return pnf.format(value);
  }
}

An example of HTML page using the above applet: GetLocaleInfo.html

使用上述applet的HTML页面示例:GetLocaleInfo.html

<!-- Header skipped for brevity -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"></script>
<script type="text/javascript">
var applet;
$(document).ready(function()
{
  applet = document.getElementById('LocaleInfo');
  $('#Results').text(applet.GetLocaleInformation());
});
</script>
<script type="text/javascript">
function DoFormatting()
{
  $('table.toFormat').each(function()
  {
    var table = $(this);
    $('td', table).each(function(cellId)
    {
      var val = $(this);
      if (val.is('.number'))
      {
        val.text(applet.FormatNumber(val.text()));
      }
      else if (val.is('.currency'))
      {
        val.text(applet.FormatCurrency(val.text()));
      }
      else if (val.is('.percent'))
      {
        val.text(applet.FormatPercent(val.text()));
      }
    });
  });
}
</script>
</head>
<body>
  <div id="Container">
    <p>Page to demonstrate how JavaScript can get locale information from Java</p>
    <div id="AppletContainer">
      <object classid="java:GetLocaleInfo.class"
          type="application/x-java-applet" codetype="application/java"
          name="LocaleInfo" id="LocaleInfo" width="0" height="0">
        <param name="code" value="GetLocaleInfo"/>
        <param name="mayscript" value="true"/>
        <param name="scriptable" value="true"/>
        <p><!-- Displayed if object isn't supported -->
          <strong>This browser does not have Java enabled.</strong>
          <br>
          <a href="http://java.sun.com/products/plugin/downloads/index.html" title="Download Java plug-in">
          Get the latest Java plug-in here
          </a> (or enable Java support).
        </p>
      </object>
    </div><!-- AppletContainer -->
    <p>
    Click on the button to format the table content to the locale rules of the user.
    </p>
    <input type="button" name="DoFormatting" id="DoFormatting" value="Format the table" onclick="javascript:DoFormatting()"/>
    <div id="Results">
    </div><!-- Results -->
<table class="toFormat">
<caption>Synthetic View</caption>
<thead><tr>
<th>Name</th><th>Value</th><th>Cost</th><th>Discount</th>
</tr></thead>
<tbody>
<tr><td>Foo</td><td class="number">3.1415926</td><td class="currency">21.36</td><td class="percent">0.196</td></tr>
<tr><td>Bar</td><td class="number">159263.14</td><td class="currency">33</td><td class="percent">0.33</td></tr>
<tr><td>Baz</td><td class="number">15926</td><td class="currency">12.99</td><td class="percent">0.05</td></tr>
<tr><td>Doh</td><td class="number">0.01415926</td><td class="currency">5.1</td><td class="percent">0.1</td></tr>
</tbody>
</table>
  </div><!-- Container -->
</body>
</html>

Tested on Firefox 3.0, IE 6, Safari 3.1 and Opera 9.50, on Windows XP Pro SP3. It works without problem with the first two, on Safari I have a strange error after init() call:

在Windows XP Pro SP3上测试Firefox 3.0,IE 6,Safari 3.1和Opera 9.50。前两个工作没有问题,在Safari上我在init()调用后有一个奇怪的错误:

java.net.MalformedURLException: no protocol:
    at java.net.URL.<init>(Unknown Source)
    at java.net.URL.<init>(Unknown Source)
    at java.net.URL.<init>(Unknown Source)
    at sun.plugin.liveconnect.SecureInvocation.checkLiveConnectCaller(Unknown Source)
    at sun.plugin.liveconnect.SecureInvocation.access$000(Unknown Source)
    at sun.plugin.liveconnect.SecureInvocation$2.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.plugin.liveconnect.SecureInvocation.CallMethod(Unknown Source)

but it still works.

但它仍然有效。

I can't get it work with Opera: the applet loads correctly, as I can see the trace of init() call in the Java console, I have no errors when JavaScript calls the Java functions (except if I add and call a method getting a JSObject parameter, curiously), but the Java functions are not called (I added trace of the calls).
I believe Liveconnect works in Opera, but I don't see yet how. I will research a bit more.
[Update] I removed references to non-existing jar file (which doesn't stop other browsers) and I got a trace of the calls, but it doesn't update the page.
Mmm, if I do alert(applet.GetLocaleInformation()); I got the information, so it might be a jQuery issue.

我无法使用Opera:applet正确加载,因为我可以在Java控制台中看到init()调用的跟踪,当JavaScript调用Java函数时我没有错误(除非我添加并调用方法)奇怪地得到一个JSObject参数,但没有调用Java函数(我添加了调用的跟踪)。我相信Liveconnect可以在Opera中运行,但我还没有看到。我会再研究一下。 [更新]我删除了对不存在的jar文件的引用(它不会阻止其他浏览器),我得到了一些调用,但它没有更新页面。嗯,如果我做警报(applet.GetLocaleInformation());我得到了信息,所以它可能是一个jQuery问题。

#7


1  

I think you have to rely on JavaScript to give you the locale settings.
But apparently JS doesn't have direct access to this information.
I see Dojo Toolkit relies on an external database to find the locale information, although it might not take in account setting changes, for example.
Another workaround I see is to have a small silent Java applet that query this information from the system, and JavaScript to get it out of Java.
I can give more information if you don't know how to do it (if you want to go this convoluted route, of course).

我认为你必须依靠JavaScript来为你提供语言环境设置。但显然JS没有直接访问这些信息。我看到Dojo Toolkit依赖于外部数据库来查找区域设置信息,例如,它可能不会考虑设置更改。我看到的另一个解决方法是使用一个小的静态Java小程序从系统中查询此信息,并使用JavaScript从Java中获取它。如果你不知道怎么做,我可以提供更多的信息(当然,如果你想走这条错综复杂的路线)。

[EDIT] So I updated my knowledge of localization support in Java...
Unlike what I thought originally, you won't have directly the decimal separator or thousand separator characters directly, like you would do with line separator or path separator: instead Java offers APIs to format the numbers or dates you provide.
Somehow, it makes sense: in Europe you often put the currency symbol after the number, some countries (India?) have a more complex rule to separate digits, etc.

[编辑]所以我更新了我在Java中的本地化支持的知识...与我原来的想法不同,你不会直接使用小数分隔符或千位分隔符,就像你使用行分隔符或路径分隔符一样:而不是Java提供API来格式化您提供的数字或日期。不知何故,它有道理:在欧洲,你经常把货币符号放在数字后面,有些国家(印度?)有一个更复杂的规则来分隔数字等。

Another thing: Java correctly finds the current locale from the system, but doesn't take information from there (perhaps for above reasons). Instead it uses its own set of rules. So if you have a Spanish locale where you replaced decimal separator with an exclamation sign, Java won't use it (but perhaps neither your application, anyway...).

另一件事:Java正确地从系统中找到当前的语言环境,但不从那里获取信息(可能由于上述原因)。相反,它使用自己的一套规则。因此,如果你有一个西班牙语语言环境,你用感叹号替换小数分隔符,Java将不会使用它(但也许你的应用程序,无论如何......)。

So I am writing an applet exposing a service (functions) to JavaScript, allowing to format numbers to the current locale. You can use it as such, using JavaScript to format numbers on the browser. Or you can just feed it with some sample number and extract the symbols from there, using them locally or feeding them back to the server.

所以我正在编写一个向JavaScript公开服务(函数)的applet,允许将数字格式化为当前语言环境。您可以这样使用它,使用JavaScript格式化浏览器上的数字。或者你可以用一些样本号来提供它并从那里提取符号,在本地使用它们或将它们反馈给服务器。

I finish and test my applet and post it there soon.

我完成并测试我的applet并很快将其发​​布到那里。

#8


1  

Even if you knew what locale this "GUI Application" is running under, you still have to figure out how it is getting the current locale, and how it is determining the decimal separator.

即使您知道这个“GUI应用程序”正在运行的区域设置,您仍然需要弄清楚它是如何获取当前区域设置的,以及它如何确定小数分隔符。

i don't know how it is done on a Mac, but on Windows applications are supposed to interrogte the user's preferences set via the Control Panel. It's quite possible this mystery applicaiton is ignoring those settings, and using their own internal setup instead.

我不知道它是如何在Mac上完成的,但在Windows应用程序上应该通过控制面板询问用户的首选项。这个神秘的应用程序很可能忽略了这些设置,而是使用自己的内部设置。

Or perhaps they're taking the current locale, and inferring the rest, rather than being told.

或许他们正在采用当前的语言环境,并推断其余的,而不是被告知。

Even then, in english, numbers are given in groups of 3 digits, with a comma separating the groups. i.e.:

即便如此,在英语中,数字以3位数组的形式给出,逗号分隔各组。即:

5,197,359,078

Unless the number was an integer that contains a phone number:

除非该数字是包含电话号码的整数:

519-735-9078

Unless of course the number was an integer that contains an account number:

除非数字是一个包含帐号的整数:

5197359078

In which case, you're back to hard-coded overridden logic.

在这种情况下,您将回到硬编码的重写逻辑。

Edit: Removed currency example, since currency has its own formatting rules.

编辑:删除货币示例,因为货币有自己的格式规则。

#9


0  

"Is there any way to do it on server side (preferably, so that I can collect statistics), or on client side?"

“有没有办法在服务器端(最好是我可以收集统计数据),或在客户端?”

No you can't. That GUI is looking at some user or machine specific settings. First, you probably do not know at what settings this UI is looking. Second, with a webapplication you will probably not be able to check these settings (clientside --> Javacsript).

不,你不能。该GUI正在查看某些用户或计算机特定设置。首先,您可能不知道此UI正在查看的设置。其次,使用Web应用程序,您可能无法检查这些设置(clientside - > Javacsript)。

#10


0  

Using other people answers I compiled the following decimal and thousand separators utility functions:

使用其他人的答案我编译了以下十进制和千位分隔符实用程序函数:

var decimalSeparator = function() {
    return (1.1).toLocaleString().substring(1, 2);
};
var thousandSeparator = function() {
    return (1000).toLocaleString().substring(1, 2);
};

Enjoy!

请享用!

#11


-3  

Another possible solution: You could use something like GeoIP (example in PHP) to determine the user's location and decide based on these information.

另一种可能的解决方案:您可以使用GeoIP(PHP中的示例)来确定用户的位置,并根据这些信息做出决定。