Remove trailing zero in Java - 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());

Related

Replacing a character in a string from another string with the same char index

I'm trying to search and reveal unknown characters in a string. Both strings are of length 12.
Example:
String s1 = "1x11222xx333";
String s2 = "111122223333"
The program should check for all unknowns in s1 represented by x|X and get the relevant chars in s2 and replace the x|X by the relevant char.
So far my code has replaced only the first x|X with the relevant char from s2 but printed duplicates for the rest of the unknowns with the char for the first x|X.
Here is my code:
String VoucherNumber = "1111x22xx333";
String VoucherRecord = "111122223333";
String testVoucher = null;
char x = 'x'|'X';
System.out.println(VoucherNumber); // including unknowns
//find x|X in the string VoucherNumber
for(int i = 0; i < VoucherNumber.length(); i++){
if (VoucherNumber.charAt(i) == x){
testVoucher = VoucherNumber.replace(VoucherNumber.charAt(i), VoucherRecord.charAt(i));
}
}
System.out.println(testVoucher); //after replacing unknowns
}
}
I am always a fan of using StringBuilders, so here's a solution using that:
private static String replaceUnknownChars(String strWithUnknownChars, String fullStr) {
StringBuilder sb = new StringBuilder(strWithUnknownChars);
while ((int index = Math.max(sb.toString().indexOf('x'), sb.toString().indexOf('X'))) != -1) {
sb.setCharAt(index, fullStr.charAt(index));
}
return sb.toString();
}
It's quite straightforward. You create a new string builder. While a x or X can still be found in the string builder (indexOf('X') != -1), get the index and setCharAt.
Your are using String.replace(char, char) the wrong way, the doc says
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
So you if you have more than one character, this will replace every one with the same value.
You need to "change" only the character at a specific spot, for this, the easiest is to use the char array that you can get with String.toCharArray, from this, this is you can use the same logic.
Of course, you can use String.indexOf to find the index of a specific character
Note : char c = 'x'|'X'; will not give you the expected result. This will do a binary operation giving a value that is not the one you want.
The OR will return 1 if one of the bit is 1.
0111 1000 (x)
0101 1000 (X)
OR
0111 1000 (x)
But the result will be an integer (every numeric operation return at minimum an integer, you can find more information about that)
You have two solution here, you either use two variable (or an array) or if you can, you use String.toLowerCase an use only char c = 'x'

Java automatic filling of ArrayList, searching for better options

I'm using this code here to automatically fill a string array list with the directory path of obj files for later use in animations, but there's a small problem with this:
private List<String> bunny_WalkCycle = new ArrayList<String>();
private int bunny_getWalkFrame = 0;
private void prepare_Bunny_WalkCycle() {
String bunny_walkFrame = "/bunnyAnimation/bunnyFrame0.obj";
while(bunny_WalkCycle.size() != 30) { // 30 obj files to loop through
if(bunny_getWalkFrame != 0) {
bunny_walkFrame =
"/bunnyAnimation/bunnyWalkAnim/bunnyWalkFrame_"+bunny_getWalkFrame+".obj";
}
bunny_WalkCycle.add(bunny_getWalkFrame);
bunny_getWalkFrame++;
}
}
Now the problem is that the naming convention in blender for animations has zeros before the actual numbers, so something like this:
bunnyWalkFrame_000001.obj
bunnyWalkFrame_000002.obj
bunnyWalkFrame_000003.obj
...
bunnyWalkFrame_000030.obj
With my prepare_Bunny_WalkCycle method I cannot account for the zeros so I would change the names and get rid of the zeros.. This may be okay for not so many frames but once I hit 100 frames it would get painfull.. So there's my question:
What would be an intelligent way to account for the zeros in the code instead of having to rename every file manually and remove them?
I think you can solve your problem with "String.format":
String blenderNumber = String.format("%06d", bunny_getWalkFrame);
Explanation:
0 -> to put leading zeros
6 -> "width" of them / amount of them
And so this would be your new bunny_walkFrame:
bunny_walkFrame = "/bunnyAnimation/bunnyWalkAnim/bunnyWalkFrame_" + blenderNumber + ".obj";
You can use String.format() to pad your numbers with zeros:
String.format("%05d", yournumber);
Here are two options. First, you can use a string formatter to create your filenames with leading zeros:
bunny_WalkCycle.add("/bunnyAnimation/bunnyFrame0.obj");
for (int frame = 1; frame <= 30; frame++) {
bunny_WalkCycle.add(
String.format("/bunnyAnimation/bunnyWalkAnim/bunnyWalkFrame_%06s.obj", frame));
}
The second option is, if you already have all the required files in the directory, you can get them all in one go:
bunny_WalkCycle.add("/bunnyAnimation/bunnyFrame0.obj");
bunny_WalkCycle.addAll(Arrays.asList(new File("/bunnyAnimation/bunnyWalkAnim").list()));
There are two ways you could do that:
Appending the right number of leading zeroes, or using a String formatter.
bunny_walkFrame = "/bunnyAnimation/bunnyWalkAnim/bunnyWalkFrame_" + String.format("%05d", bunny_getWalkFrame) + ".obj";
OR
bunny_walkFrame = "/bunnyAnimation/bunnyWalkAnim/bunnyWalkFrame_" + getLeadingZeroes(bunny_getWalkFrame) + String.valueOf(bunny_getWalkFrame) + ".obj";
where
private String getLeadingZeroes(int walk) {
String zeroes = "";
int countDigits = 0;
while (walk > 0) {
countDigits++;
walk /= 10;
}
for (int i = 1; i <= (nZeroes - countDigits); i++) {
zeroes += "0";
}
return zeroes;
}
Here ya go:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
Just specify how many digits you want. Set it to one. If it has to it will push over (so it won't cut digits off)

Efficient way of adding zeros to a String number?

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";
}
}

Convert String to Number, Java

Edit: Clarification convert any valid number encoding from a string to a number
How does one convert a string to a number, say just for integers, for all accepted integer formats, particularly the ones that throw NumberFormatException under Integer.parseInt. For example, the code
...
int i = 0xff;
System.out.println(i);
String s = "0xff";
System.out.println( Integer.parseInt(s) );
....
Will throw a NumberFormatException on the fourth line, even though the string is clearly a valid encoding for a hexadecimal integer. We can assume that we already know that the encoding is a valid number, say by checking it against a regex. It would be nice to also check for overflow (like Integer.parseInt does), but it would be okay if that has to be done as a separate step.
I could loop through every digit and manually calculate the composite, but that would pretty difficult. Is there a better way?
EDIT: a lot of people are answering this for hexidecimal, which is great, but not completely what I was asking (it's my fault, I used hexidecimal as the example). I'm wondering if there's a way to decode all valid java numbers. Long.decode is definitely great for just catching hex, but it fails on
222222L
which is a perfectly valid long. Do I have to catch for every different number format separately? I'm assuming you've used a regex to tell what category of number it is, i.e, distinguish floats, integers, etc.
You could do
System.out.println(Integer.decode(s));
You need to specify the base of the number you are trying to parse:
Integer.parseInt(s,16);
This will fail if you have that "0x" starting it off so you could just add a check:
if (s.startsWith("0x")) {
s = s.substring(2);
}
Integer.parseInt(s,16);
EDIT
In response to the information that this was not a hex specific question I would recommend writing your own method to parse out all the numbers formats you like and build in on top of Integer.decode which can save you from having to handle a couple of cases.
I would say use regex or create your own methods to validate other formats:
public static int manualDecode(String s) throws NumberFormatException {
// Match against #####L long format
Pattern p = Pattern.compile("\\d+L"); // Matches ########L
Matcher m = p.matcher(s);
if (m.matches()) {
return Integer.decode(s.substring(0,s.length()-1));
}
// Match against that weird underscore format
p = Pattern.compile("(\\d{1,3})_((\\d{3})_)*?(\\d{3})"); // Matches ###_###_###_###_###
m = p.matcher(s);
if (m.matches()) {
String reformattedString = "";
char c;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if ( c >= '0' && c <= '9') {
reformattedString += c;
}
}
return Integer.decode(reformattedString);
}
// Add as many more as you wish
throw new NumberFormatException();
}
public int parseIntExtended(String s) {
try {
return Integer.decode(s);
} catch (NumberFormatException e) {
return manualDecode(s);
}
}
Integer.decode should do the trick:
public class a{
public static void main(String[] args){
String s="0xff";
System.out.println(Integer.decode(s));
}
}
You can try using BigInteger also but sill you have to remove 0x first or replace x from 0
int val = new BigInteger("ff", 16).intValue(); // output 255

Run-length decompression

CS student here. I want to write a program that will decompress a string that has been encoded according to a modified form of run-length encoding (which I've already written code for). For instance, if a string contains 'bba10' it would decompress to 'bbaaaaaaaaaa'. How do I get the program to recognize that part of the string ('10') is an integer?
Thanks for reading!
A simple regex will do.
final Matcher m = Pattern.compile("(\\D)(\\d+)").matcher(input);
final StringBuffer b = new StringBuffer();
while (m.find())
m.appendReplacement(b, replicate(m.group(1), Integer.parseInt(m.group(2))));
m.appendTail(b);
where replicate is
String replicate(String s, int count) {
final StringBuilder b = new StringBuilder(count);
for (int i = 0; i < count; i++) b.append(s);
return b.toString();
}
Not sure whether this is one efficient way, but just for reference
for (int i=0;i<your_string.length();i++)
if (your_string.charAt(i)<='9' && your_string.charAt(i)>='0')
integer_begin_location = i;
I think you can divide chars in numeric and not numeric symbols.
When you find a numeric one (>0 and <9) you look to the next and choose to enlarge you number (current *10 + new) or to expand your string
Assuming that the uncompressed data does never contain digits: Iterate over the string, character by character until you get a digit. Then continue until you have a non-digit (or end of string). The digits inbetween can be parsed to an integer as others already stated:
int count = Integer.parseInt(str.substring(start, end));
Here is a working implementation in python. This also works fine for 2 or 3 or multiple digit numbers
inputString="a1b3s22d4a2b22"
inputString=inputString+"\0" //just appending a null char
charcount=""
previouschar=""
outputString=""
for char in inputString:
if char.isnumeric():
charcount=charcount+char
else:
outputString=outputString
if previouschar:
outputString=outputString+(previouschar*int(charcount))
charcount=""
previouschar=char
print(outputString) // outputString= abbbssssssssssssssssssssssddddaabbbbbbbbbbbbbbbbbbbbbb
Presuming that you're not asking about the parsing, you can convert a string like "10" into an integer like this:
int i = Integer.parseInt("10");

Categories