java 如何在java中将字符串数字转换为逗号分隔的整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6439447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert string numbers into comma separated integers in java?
提问by sathish
Can any one give me some predefined methods or user defined methods to convert string numbers(example: 123455) to comma separated integer value (example: 1,23,455).
谁能给我一些预定义的方法或用户定义的方法来将字符串数字(例如:123455)转换为逗号分隔的整数值(例如:1,23,455)。
采纳答案by Suhail Gupta
I assume 123455
is a String
.
我假设123455
是一个String
.
String s = 123455;
String s1 = s.substring( 0 , 1 ); // s1 = 1
String s2 = s.substring( 1 , 3 ); // s2 = 23
String s3 = s.substring( 2 , 7 ); // s3 = 455
s1 = s1 + ',';
s2 = s2 + ',';
s = s1 + s2; // s is a String equivalent to 1,23,455
Now we use static int parseInt(String str)
method to convert String into integer.This method returns the integer equivalent of the number contained in the String
specified by str
using radix 10.
现在我们使用static int parseInt(String str)
方法将字符串转换为整数。该方法返回使用基数10String
指定的包含在指定中的数字的整数等价物str
。
Here you cannot convert s ---> int
. Since int does not have commas.If you try to convert you will get the following exception java.lang.NumberFormatException
在这里你不能转换s ---> int
. 由于 int 没有逗号。如果您尝试转换,您将得到以下异常java.lang.NumberFormatException
you should use DecimalFormat
Class. http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html
你应该使用DecimalFormat
类。 http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html
回答by Divesh
int someNumber = 123456;
NumberFormat nf = NumberFormat.getInstance();
nf.format(someNumber);
回答by Ovais Khatri
use java.text.NumberFormat, this will solve your problem.
使用 java.text.NumberFormat,这将解决您的问题。
回答by sathish
Finally I found an exact solution for my needs.
最后,我找到了满足我需求的确切解决方案。
import java.math.*;
import java.text.*;
import java.util.*;
public class Mortgage2 {
public static void main(String[] args) {
BigDecimal payment = new BigDecimal("1115.37");
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
double doublePayment = payment.doubleValue();
String s = n.format(doublePayment);
System.out.println(s);
}
}
回答by talnicolas
回答by Jasonw
The result you expected that is "to comma separated integervalue", is in my opinion incorrect. However, if you are just looking for output representation, how about these lines of codes shown below? (Note, you can not parse the value return from valueToString to some data type long because it just does not make sense :) )
您期望的结果是“以逗号分隔的整数值”,在我看来是不正确的。但是,如果您只是在寻找输出表示,那么下面显示的这些代码行如何?(注意,您不能将从 valueToString 返回的值解析为某些数据类型 long 因为它没有意义:))
MaskFormatter format = new MaskFormatter("#,##,###");
format.setValueContainsLiteralCharacters(false);
System.out.println(format.valueToString(123455));