I have a string:
String x = "10";
Now I want to add .
between the numbers and print it like this
1.0
How can I achieve this?
You can split the string into the first character and the rest of the string, and then insert a dot '.'
in between, like this:
String res = x.substring(0,1)+"."+x.substring(1);
// ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^
// the first digit the rest of the string
You can also use replaceAll
to do it on longer strings, like this:
String orig = "19,28,37,46";
System.out.println(orig.replaceAll("(\\d)(\\d)", "$1.$2"));
This prints
1.9,2.8,3.7,4.6
使用DecimalFormat
类可以更好地解耦值及其表示。
如果字符串始终是 2 位数字:
String result = x.charAt(0) + "." + x.charAt(1);
this function can accepts all number and returns a dotted string, with small touches it can accepts many in other types of data an return data with options
fun getStringWithDot(nums: Int): String {
var str = ""
val istr = nums.toString()
for (ch in istr.indices){
if (ch == istr.length-1){
str += istr.substring(0,1)
}else{
str += istr.substring(ch,ch+1) + "."
}
}
return str
}
public static void main(String args[])
{
Scanner S=new Scanner(System.in);
int arr[];
int number;
number=S.nextInt();
int length=Integer.toString(number).length();
arr=new int[length];
char arr2[];
arr2=new char[length];
int count=0;
char arr3[];
arr3=new char[length];
String Q=Integer.toString(number);
for(int i=0;i<arr3.length;i++)
{
System.out.print(Q.charAt(i)+".");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.