简体   繁体   English

在java中强制点(“.”)作为小数点分隔符

[英]Force point (“.”) as decimal separator in java

I currently use the following code to print a double:我目前使用以下代码打印双精度:

return String.format("%.2f", someDouble);

This works well, except that Java uses my Locale's decimal separator (a comma) while I would like to use a point.这很有效,除了 Java 使用我的语言环境的小数点分隔符(逗号),而我想使用一个点。 Is there an easy way to do this?是否有捷径可寻?

Use the overload of String.format which lets you specify the locale:使用String.format的重载,它允许您指定语言环境:

return String.format(Locale.ROOT, "%.2f", someDouble);

If you're only formatting a number - as you are here - then using NumberFormat would probably be more appropriate.如果你只是格式化一个数字——就像你在这里一样——那么使用NumberFormat可能更合适。 But if you need the rest of the formatting capabilities of String.format , this should work fine.但是,如果您需要String.format的其余格式化功能,这应该可以正常工作。

A more drastic solution is to set your Locale early in the main().一个更彻底的解决方案是在 main() 的早期设置您的区域设置。

Like:像:

Locale.setDefault(new Locale("en", "US"));

Way too late but as other mentioned here is sample usage of NumberFormat (and its subclass DecimalFormat )太晚了,但正如这里提到的其他人是NumberFormat (及其子类DecimalFormat )的示例用法

public static String format(double num) {
    DecimalFormatSymbols decimalSymbols = DecimalFormatSymbols.getInstance();
    decimalSymbols.setDecimalSeparator('.');
    return new DecimalFormat("0.00", decimalSymbols).format(num);
 }

You can pass an additional Locale to java.lang.String.format as well as to java.io.PrintStream.printf (eg System.out.printf()):您可以将额外的 Locale 传递给 java.lang.String.format 以及 java.io.PrintStream.printf(例如 System.out.printf()):

import java.util.Locale;

public class PrintfLocales {

    public static void main(String args[]) {
        System.out.printf("%.2f: Default locale\n", 3.1415926535);
        System.out.printf(Locale.GERMANY, "%.2f: Germany locale\n", 3.1415926535);
        System.out.printf(Locale.US, "%.2f: US locale\n", 3.1415926535);
    }

}

This results in the following (on my PC):这导致以下结果(在我的 PC 上):

$ java PrintfLocales
3.14: Default locale
3,14: Germany locale
3.14: US locale

See String.format in the Java API.请参阅 Java API 中的String.format

You can use NumberFormat and DecimalFormat.您可以使用 NumberFormat 和 DecimalFormat。

Take a look at this link from Java Tutorials LocaleSpecific Formatting从 Java 教程LocaleSpecific Formatting 中查看此链接

The section titled Locale-Sensitive Formatting is what you need.标题为 Locale-Sensitive Formatting 的部分正是您所需要的。

Change the language, it worked for me.更改语言,它对我有用。

How to set eclipse console locale/language How to set eclipse console locale/language如何设置 Eclipse 控制台语言环境/语言如何设置 Eclipse 控制台语言环境/语言

I had the same issue.. 55.1 transformed to 55,10 .我有同样的问题.. 55.1转换为55,10 My quick (dirty?) fix is :我的快速(脏?)修复是:

String.format("%.2f", value).replaceAll(",",".");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM