dav*_*cks 139 java string casting
我的价格是int6位数.我希望将它显示为String带有小数点(.)的结尾处的2位数int.我想使用a float但建议String用于更好的显示输出(而不是1234.5将1234.50).因此,我需要一个函数,它将采用intas参数并返回正确格式化String的结尾,小数点为2位数.
说:
int j= 123456
Integer.toString(j);
//processing...
//output : 1234.56
Run Code Online (Sandbox Code Playgroud)
blo*_*p3r 196
正如在注释中提到的,StringBuilder可能是一个更快的实现,然后使用StringBuffer.正如Java文档中提到的:
此类提供与StringBuffer兼容的API,但不保证同步.此类设计用作StringBuffer的替代品,用于单个线程使用字符串缓冲区的位置(通常情况下).在可能的情况下,建议首先使用此类优先于StringBuffer,因为在大多数实现中它会更快.
用法:
String str = Integer.toString(j);
str = new StringBuilder(str).insert(str.length()-2, ".").toString();
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要同步,请使用具有类似用法的StringBuffer:
String str = Integer.toString(j);
str = new StringBuffer(str).insert(str.length()-2, ".").toString();
Run Code Online (Sandbox Code Playgroud)
Mik*_*sen 179
int j = 123456;
String x = Integer.toString(j);
x = x.substring(0, 4) + "." + x.substring(4, x.length());
Run Code Online (Sandbox Code Playgroud)
Ita*_*man 17
int yourInteger = 123450;
String s = String.format("%6.2f", yourInteger / 100.0);
System.out.println(s);
Run Code Online (Sandbox Code Playgroud)
使用 ApacheCommons3 StringUtils,你也可以做
int j = 123456;
String s = Integer.toString(j);
int pos = s.length()-2;
s = StringUtils.overlay(s,".", pos, pos);
Run Code Online (Sandbox Code Playgroud)
它基本上是子字符串连接,但如果您不介意使用库,或者已经依赖于 StringUtils,则它会更短
对于 Kotlin 伙计们;)来自已接受的答案(@MikeThomsen\'s)
\nfun String.insert(insertAt: Int, string: String): String {\n return this.substring(0, insertAt) + string + this.substring(insertAt, this.length)\n}\nRun Code Online (Sandbox Code Playgroud)\n测试\xe2\x9c\x85
\n"ThisTest".insert(insertAt = 4, string = "Is").should.equal("ThisIsTest")\nRun Code Online (Sandbox Code Playgroud)\n
在大多数用例中,使用StringBuilder(如已回答的)是一个很好的方法来做到这一点。但是,如果性能很重要,这可能是一个不错的选择。
/**
* Insert the 'insert' String at the index 'position' into the 'target' String.
*
* ````
* insertAt("AC", 0, "") -> "AC"
* insertAt("AC", 1, "xxx") -> "AxxxC"
* insertAt("AB", 2, "C") -> "ABC
* ````
*/
public static String insertAt(final String target, final int position, final String insert) {
final int targetLen = target.length();
if (position < 0 || position > targetLen) {
throw new IllegalArgumentException("position=" + position);
}
if (insert.isEmpty()) {
return target;
}
if (position == 0) {
return insert.concat(target);
} else if (position == targetLen) {
return target.concat(insert);
}
final int insertLen = insert.length();
final char[] buffer = new char[targetLen + insertLen];
target.getChars(0, position, buffer, 0);
insert.getChars(0, insertLen, buffer, position);
target.getChars(position, targetLen, buffer, position + insertLen);
return new String(buffer);
}
Run Code Online (Sandbox Code Playgroud)