Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何根据java中的国际数制转换整数(数字格式)_Java_String_Integer_Number Formatting - Fatal编程技术网

如何根据java中的国际数制转换整数(数字格式)

如何根据java中的国际数制转换整数(数字格式),java,string,integer,number-formatting,Java,String,Integer,Number Formatting,我想根据国际数字系统转换给定的数字。//例如: 345678 -> 345,678 12 -> 12 123 -> 123 4590 -> 4,590 下面是代码片段和 这是我的方法,我不舒服 从右开始遍历字符串 如果(length-currentIndex-1)%3==0,请在字符串中插入逗号 有什么建议吗?您可以使用: 或: 使用NumberFormat类 您可以在区域设置中传递它,然后根据需要设置数字的格式 你可以简单地使用 输出: 12345678L编号格

我想根据国际数字系统转换给定的数字。//例如:

345678 -> 345,678
12 -> 12 
123 -> 123
4590 -> 4,590
下面是代码片段和

这是我的方法,我不舒服

  • 从右开始遍历字符串
  • 如果(length-currentIndex-1)%3==0,请在字符串中插入逗号
  • 有什么建议吗?

    您可以使用:

    或:


    使用
    NumberFormat

    您可以在区域设置中传递它,然后根据需要设置数字的格式

    你可以简单地使用

    输出:

    12345678L编号格式化为12345678.00


    谢谢。我不知道格式化程序课。十进位的例子帮了大忙。谢谢你
    public static void main (String[] args) throws java.lang.Exception
    {
        int number = 345678;
        String s = Integer.toString(number);
        s = putCommas(s);
    }
    
    private String putCommas(String s) {
        // How to put commas in string after every 3rd character from right ?
    }
    
    NumberFormat.getNumberInstance(Locale.US).format(number);
    
    DecimalFormat formatter = new DecimalFormat("#,###");
    String newNumber = formatter.format(number);
    
    System.out.println (NumberFormat.getNumberInstance(Locale.US).format(1234567L));
    
    NumberFormat numberFormat = NumberFormat.getInstance();
    //allows to have number seperated by comma
    numberFormat.setGroupingUsed(true);
    
    String formattedNr = numberFormat.format(12345678L);
    System.out.println("12345678L number formatted to " + formattedNr);