[英]Padding to get specific number of digits in a number
String val = "98"
我需要獲得輸出為0000098
(7位數字)。
我需要將零填充到字符串或整數值...
val中存儲的數字是動態的,可以包含任意數字,但是輸出應始終為7位。
在groovy中,您可以像這樣填充String:
val.padLeft( 7, '0' )
這將用零填充字符串的左側,直到長度為7個字符
使用String.format
:
public class A {
public static void main(String[] args) {
System.out.println(String.format("%07d", 98)); // -> 0000098
}
}
看一下http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html ,它提供了leftpad
, rightpad
等功能。
您可以通過以下方式使用NumberFormat格式化String值:
NumberFormat formatter = new DecimalFormat("0000000");
這意味着您的字符串將根據需要用0補全。
然后,要格式化您的字符串,可以執行以下操作:
String formatRes = formatter.format(new Double(val));
因為“格式”方法需要使用double作為參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.