For example, I have a string "0.01"
. How can I get "1"
?
I had tried
String a = "0.01"
a = a.replaceAll(".", "");
a = a.replaceAll("0", "");
but this won't work as the string can be "0.0105"
and in this case, I want to keep "105"
I also tried
String a = "0.01"
b = a.substring(s.indexOf("0")+3);
this also won't work as the string can be "0.1"
which I want to keep "1"
In short, I want to remove all 0
or .
until it starts with non-0. The string is actually converted from Double. I can't simply *100
with the Double as it can be 0.1
String a = "0.01";
String[] b = a.split("\\.");
a = b[0]+b[1];
int c = Integer.parseInt(a);
You will get 1 as integer. When you want to add something you can add and then return to string like:
c = c+3;
String newa = String.valueOf(c);
System.out.println(newa);
Use the regex, [1-9][0-9]*
which means the first digit as 1-9
and then subsequent digits ( optional ) as 0-9
. Learn more about regex from Lesson: Regular Expressions .
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "0.0105";
Pattern pattern = Pattern.compile("[1-9][0-9]*");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
str = matcher.group();
}
System.out.println(str);
}
}
Output:
105
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.