Removing trialing zeros from String? - java

I have a java web service which returns a list of strings type result as below.
12341.0
4578231.0
25.0
4785555.0
347895666.0
Now how can I remove trialing zeroes? what I want is list of strings as:
12341
4578231
25
4785555
347895666
how can i do it?

Try this, this is what I used using regex.
result = result.indexOf(".") < 0 ? result : result.replaceAll("0*$", "").replaceAll("\\.$", "");
or use Decimal Format
String result = "347895666.0";
DecimalFormat decimalFormat = new DecimalFormat("###.#");
String result = decimalFormat.format(Double.valueOf(s));
System.out.println(result);

class Test
{
public static void main(String[] args) throws ParseException {
Number parse = NumberFormat.getNumberInstance().parse("12341.0");
System.out.print(parse);
}
}

Use regex:
str = str.replaceAll("\\.0+$", "");

It may help :
string.replaceFirst("[.]0*$","")

You can use the substring (Java 7) or substring (Java 8) method in Java.
String result = "12341.0";
String stripped = result.substring(0, result.indexOf("."));

Use decimal format...
Double num= Double.parseDouble("1.300");
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(num));
output: 1.3

If you are getting double from the web service you can use this
System.out.println((int)Double.parseDouble("12341.0"));

Related

How to convert string with $ sing in it to int

I have a string "$1,076.00" and I want to convert them in to int,
I capture some value $1,076.00 and saved in string called originalAmount,
and tried int edited = Integer.parseInt(originalAmount); and it gave me error java.lang.NumberFormatException: For input string: "$1,076.00"
can anyone help?
You need to remove the undesired part ($ sign) and then parse the string to double carefully since the decimal part is a locale dependent
String pay = "$1,076.00";
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse(pay.replace("$", ""));
double result = number.doubleValue();
System.out.println(result);
string sourceString = "$1,076.00";
sourceString.substring(1, sourceString.length() - 1)
int foo = Integer.parseInt(sourceString);
Try this:
String amount = "$1,076,.00";
String formatted = amount.replace("$", ""); // remove "$" sign
formatted = formatted.replace(",", ""); // remove "," signs from number
double amountDouble = Double.parseDouble(formatted); // convert to double
int amountInt = (int)amountDouble; // convert double value to int
System.out.println(amountInt); // prints out 1076
String originalAmount="$1076.00";
String amount = originalAmount.replace($,"");
int edited = Integer.parseInt(amount);
Thanks everyone yr answers help me a lot
I have come up with
originalAmount = originalAmount.substring(1);
if (originalAmount.contains("$")) {
originalAmount = originalAmount.replace("$", "");
}
newOriginalAmt = Double.parseDouble(originalAmount);
System.out.println(newOriginalAmt);
pls let me know yr thoughts

Regex to format a string in a valid big decimal value

Dear friends I'reading a csv file that contains some file like this 1.086,12. Now my problem is that I have to format it a way that allows my to create a BigDecimal, them my correct value should be 1086.12. But I could also have another value 99,11 and in this case I have to get 99.11.
I write this snippet of code:
BigDecimal bigDecimal = null;
String str = value.replace(',','.');
bigDecimal = new BigDecimal(str);
My code works just in the latter cese, Is there some regular expression that allows this?
You do not need a regex. You can/should use DecimalFormat for that:
DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.GERMAN);
DecimalFormat df= new DecimalFormat();
df.setDecimalFormatSymbols(dfs);
Double valCEWithUKFormat = df.parse(str).doubleValue();
You can use this Java code:
String[] arr = {"1.086,12", "99.11"};
for (String tok: arr) {
if (tok.matches("[^.]*\\.[^,]+,.*"))
tok= tok.replace(".", "").replace(",", ".");
System.out.println( tok );
}
output:
1086.12
99.11

Java - Format numbers in scientific notation

I want to format this String:
String number = "3.4213946120686956E-9";
to this:
String number = "3.42E-9";
Rounding to 2 decimals. How can I achieve it?
Try new DecimalFormat("0.##E0"). Javadoc: DecimalFormat
Example:
public class Test {
private static java.text.DecimalFormat sf = new java.text.DecimalFormat("0.##E0");
public static void main(String[] args) {
System.out.println(sf.format(Double.parseDouble("3.4213946120686956E-9")));
}
};
Output: 3.42E-9
This is not the most elegant solution but you could:
EX: String number = "3.4213946120686956E-9";
if the String has a period and an E in it
split the string by the period, and get the first 2 characters after the period = 42
get the last 3 characters at the end = E-9
and then just add it back together with all the characters before the period = 3 + "." + 42 + E-9
Read about DecimalFormat.
String number = "3.4213946120686956E-9";
DecimalFormat format = new DecimalFormat("#.##E0");
System.out.println(format.format(new BigDecimal(number)));

NumberFormatException when parsing Hindi numbers

I have an android application and today I have got a crash report which contains this:
This exception trigger when the application tries to parse string number which is provided by the user.
It is obvious that problem is the application cannot parse Hindi numbers! So, how can I solve this?
Regex
Using regex would be better if you want to match any unicode digits.The regex would be \\p{N}+ and here's how to use it:
Matcher m=Pattern.compile("\\p{N}+").matcher(input);
if(m.find())
{
System.out.println(m.group());
}
Locale
To answer your question you should use NumberFormat as mentioned in docs. Specify a Locale for NumberFormat.
NumberFormat nf = NumberFormat.getInstance(new Locale("hi", "IN"));
nf.parse(input);
You can use Character.getNumericValue(char).
The good thing about this method is that it can do what you need.
But to work in valid you should implement in your application support for local.
NumberFormat format = NumberFormat.getInstance(new Locale("hin","IND"));
Number parse = format.parse("१");
System.out.println(parse);
Prints 1.
Try this. This will remove non numeric characters.
Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher(str); // str is input String
while(m.find()) {
System.out.println(m.group(1));
}
If you are dealing with double(with decimal places). you can try this
String text = "123.0114cc";
String numOnly = text.replaceAll("\\p{Alpha}","");
double numVal = Double.valueOf(numOnly);
System.out.println(numVal);
Use
BigDecimal bigDecimal = new BigDecimal(YOUR_VALUE);
before applying the regex, as the BigDecimal supports 12 integers, 12.35 decimal, and 12 $ currency, 12% percentage and its localized value.
You can use the following method which receives a string and converts every Indian digit inside it to Arabic.
public static String convertAllIndianToArabic(String str)
{
for(int i=0; i<str.length(); i++)
{
if(str.charAt(i)=='٠')
str = str.substring(0, i)+"0"+str.substring(i+1);
else if(str.charAt(i)=='١')
str = str.substring(0, i)+"1"+str.substring(i+1);
else if(str.charAt(i)=='٢')
str = str.substring(0, i)+"2"+str.substring(i+1);
else if(str.charAt(i)=='٣')
str = str.substring(0, i)+"3"+str.substring(i+1);
else if(str.charAt(i)=='٤')
str = str.substring(0, i)+"4"+str.substring(i+1);
else if(str.charAt(i)=='٥')
str = str.substring(0, i)+"5"+str.substring(i+1);
else if(str.charAt(i)=='٦')
str = str.substring(0, i)+"6"+str.substring(i+1);
else if(str.charAt(i)=='٧')
str = str.substring(0, i)+"7"+str.substring(i+1);
else if(str.charAt(i)=='٨')
str = str.substring(0, i)+"8"+str.substring(i+1);
else if(str.charAt(i)=='٩')
str = str.substring(0, i)+"9"+str.substring(i+1);
}
return str;
}

Formatting Double with two dp

From my decimalForm method below, i want to convert double value 7777.54 to 7 777,54 but i am getting 7 777 54. what have missed ? result should be 7 777,54
public static String decimalForm(double value){
DecimalFormat df = new DecimalFormat("#,###,###.00");
String formatted_value = df.format(value).replaceAll(",", " ").replace(".", ",");
return formatted_value;
}
This works for me:
DecimalFormat df = new DecimalFormat("#,###,###.00");
String formatted_value = df.format(value).replaceAll("\\.", " ");
In fact i tried to print out df.format(value) and, with value=95871 i got 95.871,00
you can use
String formatted_value = String.format("$%.2f", value);
In the pattern #,###,###.00, . is the decimal separator and , is the group separator. The character used for this two separators depends on your locale.
For example, if you are french, df.format(value) will equals to 7 777,54.
This is no String.replace version
DecimalFormat df = new DecimalFormat("#,###,###.00", new DecimalFormatSymbols(Locale.FRANCE));
String s = df.format(7777.54);
System.out.println(s);
output
7 777,54

Categories

Resources