How can a String be formatted in Java?
My String contains only numbers like "1234.0" and I want to return the formatted number.
For example, given the string "1234.0" the result should be the String "1234".
You can use regular expressions as well:
String n = "1234.0";
n.replaceAll("\\.0*$", "");
try {
String formatted = String.valueOf((int)Double.parseDouble("12345.0"));
} catch (ParseException e) {
// input is not a number
}
Use DecimalFormat like this:
DecimalFormat myFormatter = new DecimalFormat("####");
String output = myFormatter.format(value);
You can find more here
Related
I am new in Android development and i am stuck at a place. I want to format my currency, I am setting to show without decimal places and with commas.
Example: right now it's showing like 23000.00. But I want the currency like 23,000; how can I do that?
I tried the formatter classes but that doesn't help me.
This is how it's set now.
public class CurrencyFormatter {
public static String setsymbol(BigDecimal data, String currency_symbol)
{
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.ENGLISH);
format.setCurrency(Currency.getInstance(currency_symbol));
String result=data+" "+" دينار";
return result;
}
}
I expect output to be (arabic text)23,000 instead of (arabic test)23000.00
Basically, you need a currency formatter object.
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
After that you can format an amount of money:
Double currencyAmount = new Double(23000.00);
String formattedOutput = currencyFormatter.format(currencyAmount);
There are more options and explanations available here on Oracle's reference document: https://docs.oracle.com/javase/tutorial/i18n/format/numberFormat.html
check this
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.getDefault());
format.setCurrency(Currency.getInstance("USA"));
String result = format.format(1234567.89);
This is the format set of usa you can change with your country code
reference check description here
Try this, it will show in this format 23,000 without decimal points, It will show thousand separator in the number.
String result = null;
try {
// The comma in the format specifier does the trick
result = String.format("%,d", Long.parseLong(data)); // use this result variable where you want to use.
result = result + " " + " دينار"; // to append arabic text, do as you were doing before.
} catch (NumberFormatException e) {
}
I have a variable defined as String,
String totalweight;
This might take values '0.00','0.12'...any deciamls and also will have 'n/a' occasionally.
Now I have to format this field in such a way that if its not a number eg: 'n/a' leave it as such else format them like below.
public String getFmtWeight()
{
NumberFormat nf = NumberFormat.getNumberInstance();
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern("#0.00");
if(Double.isNaN(Double.parseDouble(totalweight)))
return totalweight;
else
return df.format(Double.parseDouble(totalweight));
// if(!totalweight.equals("n/a"))
// return df.format(Double.parseDouble(totalweight));
// else
// return "n/a";
}
This is breaking when n/a is cast to double throws exception. However commented portion would work. But I do not want to use it since 'n/a' may change in future with different string. Is there anyother way to achieve the same ?
One solution would be to use a try-catch to account for when parsing the string as a double fails, e.g.:
public String getFmtWeight()
{
NumberFormat nf = NumberFormat.getNumberInstance();
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern("#0.00");
try {
if(Double.isNaN(Double.parseDouble(totalweight)))
return totalweight;
else
return df.format(Double.parseDouble(totalweight));
} catch ( NumberFormatException ex ) {
/* thrown when the String can't be parsed as a double */
return totalweight; // if 'totalweight' is the String you want to parse
}
}
This will handle any string that cannot be parsed into a double using parseDouble.
You can use regular expression to validate.
NumberFormat nf = NumberFormat.getNumberInstance();
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern("#0.00");
String totalweight = "n/a";
String pattern = "[0-9]*.[0-9]*";
boolean isNan = Pattern.matches(pattern, totalweight);
if(!isNan) {
System.out.println(totalweight);
}
else {
System.out.println(df.format(Double.parseDouble(totalweight)));
}
You can try this code
I'm using a NumberFormat instance to parse text using default locale.
If a string is not a valid numeric value, I have to return 0. The problem is that parse method,according to Javadocs:
Parses text from the beginning of the given string to produce a
number. The method may not use the entire text of the given string.
So, if I parse (I'm using italian locale) "BAD 123,44" I correctly get a ParseException and return 0, but if I parse "123,44 BAD", I get a value of 123.44, while I have to return 0 in this case.
And worse, if I parse "123.44 BAD", I get value 12344!
class RateCellReader {
public static final NumberFormat NUMBER_FORMAT =
NumberFormat.getNumberInstance(Locale.getDefault());
...
try {
number = NUMBER_FORMAT.parse(textValue);
} catch (ParseException e) {
number = 0;
}
...
}
How can I do an exact parse of text, or check if text correctly represent a number in default locale?
EDIT:
Getting inspired by the response linked by #yomexzo, I changed my code like this:
class RateCellReader {
public static final NumberFormat NUMBER_FORMAT =
NumberFormat.getNumberInstance(Locale.getDefault());
...
ParsePosition pos = new ParsePosition(0);
number = NUMBER_FORMAT.parse(textValue,pos);
if (textValue.length() != pos.getIndex())
number = 0;
...
}
How about this
boolean isValid;
try {
Number n = NUMBER_FORMAT.parse(s1);
String s2 = NUMBER_FORMAT.format(n);
isValid = s1.equals(s2);
}catch(ParseException e) {
isValid = false;
}
I do have Bulgarian currency in a format like +000000027511,00.I want to convert this format to 27511.00,I have tried it and got using substring combinations and regex,Is there any patterns or regex to do it in more simplified way?
Implementation I tried,
String currency= "+000000027511"; // "[1234]" String
String currencyFormatted=currency.substring(1);
System.out.println(currencyFormatted.replaceFirst("^0+(?!$)", ""));
Using Double.valueOf + DecimalFormat.format, or DecimalFormat.parse + format, or BigDecimal you can do it as this.
// method 1 (parsing to Float)
String s = "+000000027511,00".replace(",", ".");
Double f = Double.valueOf(s);
DecimalFormat df = new DecimalFormat("#########0.00");
String formatted = df.format(f);
System.out.println(formatted);
// method 2 (parsing using Decimal Format)
s = "+000000027511,00";
DecimalFormat df2 = new DecimalFormat("+#########0.00;-#########0.00");
Number n = df2.parse(s);
df = new DecimalFormat("#########0.00");
formatted = df.format(n);
System.out.println(formatted);
// method 3 (using BigDecimal)
BigDecimal b = new BigDecimal(s.replace(",", "."));
b.setScale(2, RoundingMode.HALF_UP);
System.out.println(b.toPlainString());
Will print
27511.00
27511.00
27511.00
Something like this:
String s = "+000000027511,00";
String r = s.replaceFirst("^\\+?0*", "");
r = r.replace(',', '.');
Try
String s = "+000000027511,00";
s = s.replace("+", "").replaceAll("^0+", "").replace(',', '.');
System.out.println(s);
I'm using DecimalFormat to parse / validate user input. Unfortunately it allows characters as a suffix while parsing.
Example code:
try {
final NumberFormat numberFormat = new DecimalFormat();
System.out.println(numberFormat.parse("12abc"));
System.out.println(numberFormat.parse("abc12"));
} catch (final ParseException e) {
System.out.println("parse exception");
}
Result:
12
parse exception
I would actually expect a parse exception for both of them. How can I tell DecimalFormat to not allow input like "12abc"?
From the documentation of NumberFormat.parse:
Parses text from the beginning of the given string to produce a number. The method may not use the entire text of the given string.
Here is an example that should give you an idea how to make sure the entire string is considered.
import java.text.*;
public class Test {
public static void main(String[] args) {
System.out.println(parseCompleteString("12"));
System.out.println(parseCompleteString("12abc"));
System.out.println(parseCompleteString("abc12"));
}
public static Number parseCompleteString(String input) {
ParsePosition pp = new ParsePosition(0);
NumberFormat numberFormat = new DecimalFormat();
Number result = numberFormat.parse(input, pp);
return pp.getIndex() == input.length() ? result : null;
}
}
Output:
12
null
null
Use the parse(String, ParsePosition) overload of the method, and check the .getIndex() of the ParsePosition after parsing, to see if it matches the length of the input.