如何在java中将字符串数转换为逗号分隔的整数? [英] How to convert string numbers into comma separated integers in java?
问题描述
任何人都可以给我一些预定义的方法或用户定义的方法来将字符串数字(例如:123455)转换为逗号分隔的整数值(例如:1,23,455)。
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
是字符串
。
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
现在我们使用 static int parseInt(String str)
将String转换为整数的方法。此方法返回由<$指定的 String
中包含的数字的等效整数c $ c> str 使用基数10.
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.
这里你不能转换 s ---> int
。由于int没有逗号。如果你尝试转换,你将得到以下异常 java.lang.NumberFormatException
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
你应该使用 DecimalFormat
类。 http://download.oracle.com/javase /1.4.2/docs/api/java/text/DecimalFormat.html
这篇关于如何在java中将字符串数转换为逗号分隔的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!