Efficient way of adding zeros to a String number? - java

I would like to turn all values into the following number format, x.xxx. I am doing this fine by using a while loop and concatenating 0 to string values that do not have the correct length. However, I would like to know if there is a more efficient way of doing this. To be more clear of what I am trying to do, here are some examples.
Ex1--Change a string value such as 2.5 to 2.500
Ex2--Change a string value such as 2.51 to 2.510.
This is how I am currently doing this.
while (str.length() < 5) {
str= str+ "0";
}

You can use DecimalFormat
DecimalFormat decimalFormat = new DecimalFormat("0.000");
System.out.println(decimalFormat.format(2.5));

Wow,that was an amazing one Reimeus!
Anywy,how is this ? :P
int totalLenght = str.length();
if(totalLenght>5){
str = str.substring(0,5);
}else{
int remLength = 5 - totalLenght;
for(int i=0;i<remLength;i++){
str = str +"0";
}
}

Related

String.format() for string and numbers in Java

I will prepare String for use substring function and i need to have always 4 characters. In stackoverflow I found code like this but it is works only for numbers.
writeHead = String.format("%04d", writeHead);
But in my case i need to do this same for text + numbers.
12a --> 012a
String head = "12a";
String writeHead = String.format("%04d", head);//doesnt work
//need 012a as String
String.format is not good if yor text/number pattern is fixed (i.e. all your numbers ends with letter a?).
A quick and dirty left padding with zeroes:
String head="12a";
String writeHead = "0000"+head;
writeHead=writeHead.substring(writeHead.length()-4);
a simple thing like this will do
String head = "12a";
while(head.length < 4){
head += "0"+head;
}
just check the length and append
int head = 12;
String writeheader = String.format("0%da", head);
or
String header = 12a;
String writeHeader = String.format("0%s", head);

Number format exception in Java: unknown hex number

I`m working on a project and I had to convert a hex String to a binary String I used a lot of methods but the code below was the most useful to me although this code creates an unknown hex number "l" which looks like 1 but is not one, does some one know what this thing is(l)? and how did it appear and how to fix it and convert it to "1" ?
public String hexToBin(String hex){
String bin =new String();
String binFragment =new String();
int iHex;
hex = hex.trim();
hex = hex.replaceFirst("0x","");
for(int i = 0; i < hex.length(); i++){
iHex = Integer.parseInt(""+hex.charAt(i),16);
binFragment = Integer.toBinaryString(iHex);
while(binFragment.length() < 4){
binFragment = "0" + binFragment;
}
bin += binFragment;
}
You should use Integer.decode() instead of Integer.parseInt() as it handles hex strings as well.
See; http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#decode(java.lang.String)
Use BigInteger.toString(radix). The radix being what base you want to use. So with binary, also known as base2, fill in 2.
static String hexToBin(String s) {
return new BigInteger(s, 16).toString(2);
}

convert string to int in java

i have a string that has a int value in it. i just want to extract the int value from the string and print.
String str="No. of Days : 365";
String daysWithSplChar = str.replaceAll("[a-z][A-Z]","").trim();
char[] ch = daysWithSplChar.toCharArray();
StringBuffer stb = new StringBuffer();
for(char c : ch)
{
if(c >= '0' && c <= '9')
{
stb.append(c);
}
}
int days = Integer.ParseInt(stb.toString());
is there any better way than this. please let me know.
try String.replaceAll
String str = "No. of Days : 365";
str = str.replaceAll(".*?(\\d+).*", "$1");
System.out.println(str);
you will get
365
Another way of using regex (other than the way suggested by #EvgeniyDorofeev) which is closer to what you did:
str.replaceAll("[^0-9]",""); // give you "365"
which means, replace everything that is not 0-9 with empty string (or, in another word, remove all non-digit characters)
This is meaning the same, just a matter of taste which one is more comfortable to you:
str.replaceAll("\\D",""); // give you "365"
Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+");
int integer = in.nextInt();
This will get you the integer
following code gives you integer value
String str = "No. of Days : 365";
str = str.replaceAll(".*?(\\d+)", "$1");
System.out.println(str);
Integer x = Integer.valueOf(str);//365 in integer type
System.out.println(x+1);//output 366

Remove trailing zero in Java

I have Strings (from DB), which may contain numeric values. If it contains numeric values, I'd like to remove trailing zeros such as:
10.0000
10.234000
str.replaceAll("\\.0*$", ""), works on the first one, but not the second one.
A lot of the answers point to use BigDecimal, but the String I get may not be numeric. So I think a better solution probably is through the Regex.
there are possibilities:
1000 -> 1000
10.000 -> 10 (without point in result)
10.0100 -> 10.01
10.1234 -> 10.1234
I am lazy and stupid, just
s = s.indexOf(".") < 0 ? s : s.replaceAll("0*$", "").replaceAll("\\.$", "");
Same solution using contains instead of indexOf as mentioned in some of the comments for easy understanding
s = s.contains(".") ? s.replaceAll("0*$","").replaceAll("\\.$","") : s
Use DecimalFormat, its cleanest way
String s = "10.1200";
DecimalFormat decimalFormat = new DecimalFormat("0.#####");
String result = decimalFormat.format(Double.valueOf(s));
System.out.println(result);
Kent's string manipulation answer magically works and also caters for precision loss, But here's a cleaner solution using BigDecimal
String value = "10.234000";
BigDecimal stripedVal = new BigDecimal(value).stripTrailingZeros();
You can then convert to other types
String stringValue = stripedVal.toPlainString();
double doubleValue = stripedVal.doubleValue();
long longValue = stripedVal.longValue();
If precision loss is an ultimate concern for you, then obtain the exact primitive value. This would throw ArithmeticException if there'll be any precision loss for the primitive. See below
int intValue = stripedVal.intValueExact();
String value = "10.010"
String s = new DecimalFormat("0.####").format(Double.parseDouble(value));
System.out.println(s);
Output:
10.01
I find all the other solution too complicated. Simply
s.replaceFirst("\\.0*$|(\\.\\d*?)0+$", "$1");
does the job. It tries the first alternative first, so that dot followed by all zeros gets replaced by nothing (as the group doesn't get set). Otherwise, if it finds a dot followed by some digits (as few as possible due to the lazy quantifier *?) followed by some zeros, the zeros get discarded as they're not included in the group. It works.
Warning
My code relies on my assumption that appending a unmatched group does nothing. This is true for the Oracle implementation, but not for others, including Android, which seem to append the string "null". I'd call the such implementations broken as it just may no sense, but they're correct according to the Javadoc.
The following works for all the following examples:
"1" -> "1"
"1.0" -> "1"
"1.01500" -> "1.015"
"1.103" -> "1.103"
s = s.replaceAll("()\\.0+$|(\\..+?)0+$", "$2");
What about replacing
(\d*\.\d*)0*$
by
\1
?
You could replace with:
String result = (str.indexOf(".")>=0?str.replaceAll("\\.?0+$",""):str);
To keep the Regex as simple as possible. (And account for inputs like 1000 as pointed out in comments)
My implementation with possibility to select numbers of digits after divider:
public static String removeTrailingZero(String number, int minPrecise, char divider) {
int dividerIndex = number.indexOf(divider);
if (dividerIndex == -1) {
return number;
}
int removeCount = 0;
for (int i = dividerIndex + 1; i < number.length(); i++) {
if (number.charAt(i) == '0') {
removeCount++;
} else {
removeCount = 0;
}
}
int fracLen = number.length() - dividerIndex - 1;
if (fracLen - removeCount < minPrecise) {
removeCount = fracLen - minPrecise;
}
if (removeCount < 0) {
return number;
}
String result = number.substring(0, number.length() - removeCount);
if (result.endsWith(String.valueOf(divider))) {
return result.substring(0, result.length() - 1);
}
return result;
}
In addition to Kent's answer.
Be careful with regex in Kotlin. You have to manually write Regex() constructor instead of a simple string!
s = if (s.contains("."))
s.replace(Regex("0*\$"),"").replace(Regex("\\.\$"),"")
else s
Try to use this code:
DecimalFormat df = new DecimalFormat("#0.#####");
String value1 = df.format(101.00000);
String value2 = df.format(102.02000);
String value3 = df.format(103.20000);
String value4 = df.format(104.30020);
Output:
101
102.02
103.2
104.3002
Separate out the fraction part first. Then you can use the below logic.
BigDecimal value = BigDecimal.valueOf(345000);
BigDecimal div = new BigDecimal(10).pow(Integer.numberOfTrailingZeros(value.intValue()));
System.out.println(value.divide(div).intValue());

Java String Multiplication [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Can I multiply strings in java to repeat sequences?
In Python, we can easily multiply the stings.
count = 10
print '*' * count
Is there any similar option available in Java?
You can use Dollar for your purposes(Java API that unifies collections, arrays, iterators/iterable, and char sequences.)
String str = $("*").repeat(count);
In this way you will get result "**********" as you want.
Java doesn't have that feature for now.
char[10] c = new char[10];
Arrays.fill(c, '*');
String str = new String(c);
To avoid creating a new String everytime.
How about this??
System.out.println(String.format("%10s", "").replace(' ', '*'));
This gives me output as **********.
I believe this is what you want...
Update 1
int yournumber = 10;
System.out.println(String.format("%" + yournumber + "s","*").replace(' ', '*'));
Good Luck!!!
The simplest way to do that in Java is to use a for() loop:
String s = "";
for (int i = 0; i < 10; i++) {
s += "*";
}
System.out.println(s);

Categories