[英]how to prefix to a primitive data type
在這里我有一個問題。 我希望用戶輸入一些數字,然后將輸入轉換為字符串,然后計算字符串的長度,如果小於8,我想在輸入中添加更多零以使其為8這樣我就可以做一些職員。 我試圖使用小數格式,但無法正常工作。 請幫助 。
提前致謝
int s=Integer.parseInt(s1.readLine());
String news=String.valueOf(s);
if(news.length()<8){
DecimalFormat myformat=new DecimalFormat("00000000");
String out= myformat.format(s);
int onth=(Integer.valueOf(out)).intValue();
s=onth;
}else{
System.out.format("your number is: %d\n",s);
不用使用DecimalFormat。
將格式更改為以下格式
System.out.format("your number is: %08d\n",s)
%08d將以零開頭,寬度為8。
這只會以您要求的格式顯示數字。 如該線程其他地方所述,將其視為數字將刪除前導零。
但是,如果要將其存儲在String變量中,則可以使用
String intString = String.format("%08d", s);
存儲它。
由於您特別需要在子字符串之間獲取一系列數字,因此以下代碼將滿足您的要求。
private static int getSubNumber(int startIndex, int stopIndex, int number) {
String num = String.format("%08d", number);
return Integer.parseInt(num.substring(startIndex, stopIndex));
}
如果傳入要轉換的數字,它將把它更改為字符串,然后將傳入的兩個索引之間的子字符串轉換回數字
System.out.println(getSubNumber(2,5,12345678)); // = 345
System.out.println(getSubNumber(2,5,12345)); // = 12
System.out.println(getSubNumber(2,5,123)); // = 0
這是非包容性的,getSubNumber(2,5,...)獲取位置2、3和4 NOT 5處的值。
對於144的示例,位置2、3、4和5使用起始索引2,終止索引6
System.out.println(getSubNumber(2,6,144)); // = 1
即使您將int前綴為零,實際值也會更改為原始值。 如果要填充,則必須使用字符串。 out變量將為您提供結果。
根據評論更新
import java.util.Scanner;
public class SquareSubString {
public static void main(String[] args) {
String userInputSquare = getSquaredInput();
int digits2to5 = Integer.parseInt(userInputSquare.substring(2, 6));
System.out.println("Squre of digits 2 to 5 is : " + (digits2to5 * digits2to5));
}
private static String getSquaredInput() {
System.out.println("Enter a number : ");
Scanner in = new Scanner(System.in);
int input = in.nextInt();
in.close();
return String.format("%08d", (input * input));
}
}
如果需要在值后面加上0
,則可以將其乘以10 pow
0的數量:
int result = Integer.parseInt(news);
if(news.length()<8){
int diff = 8 - news.length();
result = result * Math.pow(10, diff); // ==> result = result * 10^(8 - news.length())
}
我認為這是最簡單的方法。
編輯 Ahhh,是的...問題中有prefix
。 沒關系!
DecimalFormat是按照我們提供模式的方式來格式化數字。
並添加零,請按照下列步驟操作: 在字符串中添加前導零
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.