Number Format nf = NumberFormat.getNumberInstance(Locale.US);
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern("$###,###.###");
String format_val=df.format(4596.37);
num = new jxl.write.Number(i, j,Double.parseDouble(format_val),arial10format);
here I'm getting NumberFormatException :
java.lang.NumberFormatException: For input string: "$4,596.37"
how to solve this one?
What I "think" you want (I've not tried this) is to let the cell take care of the formatting, for example...
NumberFormat decimalNo = new NumberFormat("$###,###.###");
WritableCellFormat numberFormat = new WritableCellFormat(decimalNo);
//write to datasheet
Number numberCell = new Number(i, j, 4596.37, numberFormat);
excelSheet.addCell(numberCell);
Take a look at WritableCellFormat for more details
What you've tried to do is...
Convert the double value 4596.37 to a String, with the format of $###,###.###
Try and convert $4,596.37 back to a double...which fails as the String you've passed to does not conform to the requirements of a double...
A number has no concept of format, that's what formatters are for. In this case, however, the Excel cell has it's own internal formatting capabilities which can take care of this for you
you can use the same DecimalFormat instance you used to create the string to parse it too by using the parse() method
see the javaDoc for more details
http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html#parse(java.lang.String,%20java.text.ParsePosition)
Related
I'm taking a value from the mobile application which I'm getting in string format something like "$000"(which actually $0.00 ) similarly I want to convert all the value into two decimal place say if I get "$279"(which is in application actually $2.79)
I don't know the correct approach because further in I have compair this value to some other string.
so I want to keep this as String but at the same time I want to put decimal after two place always whatever the number.
I tried to Decimal formatter for money but gave me "object as a number format" exception
sends
String accLastFourDigits, getCurrAmt, currAmt;
getCurrAmt = getDriver().findElement(by("overview.current_balance")).getText();
DecimalFormat money = new DecimalFormat("$0.00");
currAmt = money.format(getCurrAmt);
You could use builtin NumberFormat provided by JAVA to parse different country Currencies as shown below. Also I am dividing the resulting number by 100, so as to satisfy the requirement, that $978 is read as 9.78.
NumberFormat usFormat = NumberFormat.getCurrencyInstance(Locale.US);
String currencyValue = "$100";
try {
System.out.println(usFormat.parse(currencyValue).intValue()/100);
}catch(ParseException e) {
e.printStackTrace();
}
Here, I am setting the currency to US and then parsing a string with dollar sign.
You could also use the format method of NumberFormat to print the currency value in respective currency formats, as shown below
NumberFormat usFormat = NumberFormat.getCurrencyInstance(Locale.US);
String currencyValue = "$100";
try {
Number value = usFormat.parse(currencyValue).intValue()/100;
System.out.println("Number value : " + value);
System.out.printf("In Currency : "+usFormat.format(value));
}catch(ParseException e) {
e.printStackTrace();
}
You have this exception because format method expect number type argument. What you need to do then is to remove all non digits characters from the input string
getCurrAmt = getCurrAmt.replaceAll("[^\\d.]", ""); // please note that replaceAll method has poor performance
and parse it to Integer when calling format method
money.format(Integer.parseInt(getCurrAmt))
As pointed out replaceAll method is not very efficient because it needs to compile Pattern every single time and it's better to use Matcher - you can read about this in this topic:
String replaceAll() vs. Matcher replaceAll() (Performance differences)
How about this?
String inputStr = "$279";
NumberFormat usCurrency = NumberFormat.getCurrencyInstance(Locale.US);
usCurrency.setParseIntegerOnly(true);
long num = (Long)usCurrency.parse(inputStr);
BigDecimal amount = new BigDecimal(num);
amount = amount.scaleByPowerOfTen(-2);
log.info("amount: {}", usCurrency.format(amount));
I would like to convert a number such as the following:
2937998.7397271004
to look like this:
2.937.998,73
My attempt of achieving this looks as following, but the result still looks the same:
DecimalFormat decimalFormat = new DecimalFormat("###.###.###.###,00");
def val = decimalFormat.format(cell.getNumericCellValue().doubleValue())
return val
One way to do is to use a locale which supports your formatting pattern. For example Locale.GERMAN is in line with what you are expecting
DecimalFormat df = new DecimalFormat("###,###.00",
DecimalFormatSymbols.getInstance(Locale.GERMAN));
df.format(2937998.7397271004); // 2.937.998,74
You should definitely use Locale for this issue. And in your case formatting is german:
import java.text.NumberFormat
NumberFormat numberFormat = NumberFormat.getInstance(Locale.GERMAN);
println numberFormat.format(2937998.7397271004)
Although I am not familiar with groovy as far as I know it still utilizes the java libraries.
You cannot utilize multipled .'s on a standard DecimalFormat as can be seen in the documentation for the java class: Documentation.
So the following line of code needs to changed to:
DecimalFormat decimalFormat = new DecimalFormat("###,###,###,###.00");
Which will respond with 2.937.998,74 utilizing the provided value of 2937998.7397271004.
If you want to do it as 2.937.998,74 you can, again at least in java, do the following.
DecimalFormat decimalFormat = new DecimalFormat("###,###,###,###.00");
DecimalFormatSymbols custom = new DecimalFormatSymbols();
custom.setDecimalSeparator(',');
custom.setGroupingSeparator('.');
decimalFormat.setDecimalFormatSymbols(custom);
String val = decimalFormat.format(cell.getNumericCellValue().doubleValue());
Or use the locale as other aswers sugest.
This bit of code
DecimalFormat formatter = new DecimalFormat("0.00");
return formatter.format(-0.001);
returns
"-0.00"
I would really prefer (and expect) "0.00"
I know I can fix this by writing a subclass of DecimalFormat, but is there a way to do this using the standard DecimalFormat?
EDIT: I only wan't to change the particular case where the result is "-0.00". All other negative values should remain unchanged, eg: -9.1 -> "-9.10"
You could test the string when it's returned.
I don't believe formatting will manipulate the value.
It can only format it. Perhaps you can round it first, and then format it?
DecimalFormat formatter = new DecimalFormat("0.00");
double x = -0.001;
double y = Math.round(x*100.0)/100.0;
return formatter.format(y);
I have a simple EditText, which allows the user to enter a number such as 45.60 (example for American Dollar). I then format this number using the following method:
public String format() {
NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.getDefault());
return formatter.format(amount.doubleValue());
}
And on my Android phone, the language is set to English (United States) - hence the Locale.getDefault() should return the US locale (and it does).
Now the edit text is correctly updated to: $45.60 (hence formatting the entered number works).
However if I attempt to parse the above String "$45.60" using the following method:
NumberFormat numberFormat = NumberFormat.getInstance(Locale.getDefault());
Number result = numberFormat.parse("$45.60");
It fails with:
java.lang.IllegalArgumentException: Failed to parse amount $45.60 using locale en_US.
If I set my phone to English/ UK, formatting this "45.60" to "£45.60" works correctly (as for US), however parsing "£45.60" fails, just as it does for the above US sample.
However, if I set my phone to German (Germany), formatting "45,60" to "45,60€" works correctly, AND parsing "45,60€" works correctly as well!
The only difference I see between those three currencies: The Euro is appended to the amount, while the Dollar and the Pound are prepended to the amount.
Does anyone have an idea, why the same code works for Euro, but not for Pound and Dollar? Am I missing something?
I also created a unit test, to reproduce the issue:
public void testCreateStringBased() throws Exception {
// For German locale
CurrencyAmount amount = new CurrencyAmount("25,46€", Locale.GERMANY);
assertEquals(25.46, amount.getAsDouble());
// For French locale
amount = new CurrencyAmount("25,46€", Locale.FRANCE);
assertEquals(25.46, amount.getAsDouble());
// For US locale
amount = new CurrencyAmount("$25.46", Locale.US);
assertEquals(25.46, amount.getAsDouble());
// For UK locale
amount = new CurrencyAmount("£25.46", Locale.UK);
assertEquals(25.46, amount.getAsDouble());
}
CurrencyAmount basically wraps the code I posted for parsing currency strings, except that it takes the given locale instead of the default locale. In the above example, the test succeeds for the GERMANY and FRANCE locale but fails for US and UK locale.
Since the answers that have been suggested thus far, did not completely solve the problem, I took a painfully amateurish approach:
String value = "$24,76"
value = value.replace(getCurrencySymbol(locale), StringUtils.EMPTY);
NumberFormat numberFormat = NumberFormat.getInstance(locale);
Number result = numberFormat.parse(value);
So now I simply strip the String value off it's currency symbol... This way I can process everything I want, such as: 45.78 or 45,78 or $45.78 or 45,78€ ....
Whatever the input, the currency symbol is simply stripped and I end up with the plain number. My unittests (see OP) now complete successfully.
If anyone comes up with something better, please let me know.
Try following:
NumberFormat numberFormat = new DecimalFormat("¤#.00", new DecimalFormatSymbols(Locale.UK));
numberFormat.parse("£123.5678");
¤ - currency sign, expects matches with currency symbol by Locale.
other pattern symbols you can see by following link http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html
Try NumberFormat.getCurrencyInstance().parse() instead of NumberFormat.getInstance().parse().
You must know the locale of the string you wish to parse in order to have a locale-aware parser. The GBP string parse to a numeric ONLY when the NumberFormat's locale is en_GB; there is no such thing as a "universal" parser.
For example, how does the string "12.000" parse? For en-us, the answer is twelve; for de-de, the answer is twelve-thousand.
Always use NumberFormat.getCurrencyInstance( java.util.Locale ) to parse currency amounts.
I'm using below adapted from https://dzone.com/articles/currency-format-validation-and
import java.math.BigDecimal;
import org.apache.commons.validator.routines.*;
BigDecimalValidator currencyValidator = CurrencyValidator.getInstance();
BigDecimal parsedCurrency = currencyValidator.validate(currencyString);
if ( parsedCurrency == null ) {
throw new Exception("Invalid currency format (please also ensure it is UTF-8)");
}
If you need to insure the correct Locale is being used per user look at
Change locale on login
Sorry, but any answer provided are misleading. This is what I would call a BUG in Java.
An example like this explains it better. If I want to print a value in EUR using Locale.US and then I parse it again, it fails unless I specify on the DecimalFormat the currency (EUR). Using dollars, it works:
DecimalFormat df = new DecimalFormat("¤#,##0.00", new DecimalFormatSymbols(Locale.US));
df.setCurrency(Currency.getInstance("EUR"));
BigDecimal value = new BigDecimal("1.23");
String text = df.format(value);
System.out.println(text);
DecimalFormat df2 = new DecimalFormat("¤#,##0.00", new DecimalFormatSymbols(Locale.US));
df2.setParseBigDecimal(true);
BigDecimal parsed = (BigDecimal) df2.parse(text);
BigDecimalAsserts.assertBigDecimalEquals("parsed value is the same of the original", value, parsed);
i want to apply format mask like "#0" to my number field which is string like "6000",
i tried different types of formatting,but it didnt help,can anyone tell me how to handle this in android please
I am looking for something like when i do this formatString("6000", "#,##0.00") it should give me the formatted output 6,000.00
This should help:
String yourString = "6000";
double value = Double.valueOf(yourString);
DecimalFormat df = new DecimalFormat("#,##0.00");
System.out.println(df.format(value));
Just convert your string "6000" to a number e.g.
double d = Double.parseDouble("6000");
Then use DecimalFormat like explained here: How do I format a number in Java?