Is there a Java parsing library similar to DecimalFormat? I am unable to do what I want with DecimalFormat and regular expressions.
I need to be able to:
Parse only an integer (DecimalFormat needs more settings than just pattern)
Parse decimal (precise no rounding)
Parse numbers like 123,456.789. (DecimalFormat for ###,###.### accepts "123456789" as well)
You could try treating it like a String and tokenizing it.
str.split("\\.") will split out the decimal side and then substring it to your precision, then on the number side you could split(",")
This is quite a bit of manual parsing work though...
I would use Regexp and NumberFormat:
Map<Pattern,NumberFormat> POSSIBLE_FORMATS = ...;
String input = ...;
Number value = null;
for (Map.Entry<Pattern,NumberFormat> possible : POSSIBLE_FORMATS.entrySet()) {
if (possible.getKey().matcher(input).matches()) {
value = possible.getKeValue().parse(input);
break;
}
}
if (value == null) {
throw new IllegalArgumentExcption("no valid input format: " + input);
}
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 have a string that I'm trying to parse into a BigDecimal. I'm using the following regex to strip all non currency symbols with the exception of -,.()$. Once it has been stripped, I'm then trying to create a BigDecimal with the remaining value. The problem begins when a negative value comes across in brackets. Does anybody have any suggestions on how to repair this instance?
(1000.00) fails
I'm assuming I must somehow convert the brackets to a negative sign.
code sample.
public BigDecimal parseClient(Field field, String clientValue, String message) throws ValidationException {
if (clientValue == null) {
return null;
}
try {
clientValue = clientValue.replaceAll( "[^\\d\\-\\.\\(\\)]", "" );
return new BigDecimal(clientValue.toString());
} catch (NumberFormatException ex) {
throw new ValidationException(message);
}
}
You will need to detect the ( and ) characters yourself, then strip them out, create a BigDecimal from the rest of the string, and negate it.
if (clientValue.startsWith('(') && clientValue.endsWith(')'))
{
return new BigDecimal(clientValue.substring(1, clientValue.length() - 1)).negate();
}
else
{
return new BigDecimal(clientValue);
}
What makes you think parentheses are correctly interpreted by BigDecimal? (1000.00) is incorrect input according to the documentation. You must use - symbol (-1000.00). Supported format is strictly defined in JavaDoc. In general it's optional symbol (+ or -) followed by digits, dot (.) and exponent.
For example this is valid input: -1.1e-10.
DecimalFormat is a more appropriate tool for the job:
DecimalFormat myFormatter = new DecimalFormat("¤#,##0.00;(¤#,##0.00)");
myFormatter.setParseBigDecimal(true);
BigDecimal result = (BigDecimal) myFormatter.parse("(1000.00)");
System.out.println(result); // -1000.00 for Locale.US
System.out.println(myFormatter.parse("($123,456,789.12)")); // -123456789.12
As you can see, not only will it deal with negative patterns, but also with currency signs, decimal and grouping separators, localization issues, etc.
Take a look at The Java Tutorials: Customizing Formats for further info.
I'm getting NumberFormatException when I try to parse 265,858 with Integer.parseInt().
Is there any way to parse it into an integer?
Is this comma a decimal separator or are these two numbers? In the first case you must provide Locale to NumberFormat class that uses comma as decimal separator:
NumberFormat.getNumberInstance(Locale.FRANCE).parse("265,858")
This results in 265.858. But using US locale you'll get 265858:
NumberFormat.getNumberInstance(java.util.Locale.US).parse("265,858")
That's because in France they treat comma as decimal separator while in US - as grouping (thousand) separator.
If these are two numbers - String.split() them and parse two separate strings independently.
You can remove the , before parsing it to an int:
int i = Integer.parseInt(myNumberString.replaceAll(",", ""));
If it is one number & you want to remove separators, NumberFormat will return a number to you. Just make sure to use the correct Locale when using the getNumberInstance method.
For instance, some Locales swap the comma and decimal point to what you may be used to.
Then just use the intValue method to return an integer. You'll have to wrap the whole thing in a try/catch block though, to account for Parse Exceptions.
try {
NumberFormat ukFormat = NumberFormat.getNumberInstance(Locale.UK);
ukFormat.parse("265,858").intValue();
} catch(ParseException e) {
//Handle exception
}
One option would be to strip the commas:
"265,858".replaceAll(",","");
The first thing which clicks to me, assuming this is a single number, is...
String number = "265,858";
number.replaceAll(",","");
Integer num = Integer.parseInt(number);
Or you could use NumberFormat.parse, setting it to be integer only.
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/NumberFormat.html#parse(java.lang.String)
Try this:
String x = "265,858 ";
x = x.split(",")[0];
System.out.println(Integer.parseInt(x));
EDIT :
if you want it rounded to the nearest Integer :
String x = "265,858 ";
x = x.replaceAll(",",".");
System.out.println(Math.round(Double.parseDouble(x)));
I am using java big decimal as follwing:
class test bigDecimal{
private BigDecimal decimalResult;
public boolean iterate(String value) {
if (value == null) {
return true;
}
System.out.println("value is: " + value);
BigDecimal temp = new BigDecimal(value);
System.out.println("temp val is: " + temp);
if (decimalResult == null) {
decimalResult = temp;
} else {
decimalResult = decimalResult.add(temp);
}
return true;
}
}
all the strings that I am using to create big Decimal have scale of 6. For eg: 123456.678000, 456789.567890
But If I give a big list of strings as input and check the sum, I get output with 8 digits after decimal point. for eg. something like: 2939166.38847228.
I wonder why does BigDecimal change this scale ? all my input has scale of 6.
Any inputs are appreciated.
-thanks
Please read the javadoc for BigDecimal:
http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html
Internally all BigDecimals get converted to a some internal format.
If you want to get a specific format you have to call it appropriate.
You could use scaleByPowerOfTen(int n) with n=6 for example
Oh, and by the way never use new BigDecimal, use BigDecimal.valueOf instead.
EDIT:
NumberFormat numberFormat = NumberFormat.getInstance(); // use a locale here
String formated = df.format(myUnformatedBigDecimal);
It is not a problem of internal representation. This way the BigDecimal.toString() works. It calls layoutChars(true) - the private method that formats number. It has hard coded scale of 6. But I think it does not matter. You do not really have to pint all digits. BigDecimal provides ability to calculate high precision numbers. That's what it does.
Big decimal is giving an exact output, but that output is more accurate than 6 digits, so the best way to get 6 digit output is removing the last 2 decimals by converting the BigDecimal into string and doing something like that:
String myOutput = new
BigDecimal("1000.12345678").toString();
myOutput = myOutput.substring(myOutput.length-2,
myOutput.length);
What is the best way to format the following number that is given to me as a String?
String number = "1000500000.574" //assume my value will always be a String
I want this to be a String with the value: 1,000,500,000.57
How can I format it as such?
You might want to look at the DecimalFormat class; it supports different locales (eg: in some countries that would get formatted as 1.000.500.000,57 instead).
You also need to convert that string into a number, this can be done with:
double amount = Double.parseDouble(number);
Code sample:
String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");
System.out.println(formatter.format(amount));
This can also be accomplished using String.format(), which may be easier and/or more flexible if you are formatting multiple numbers in one string.
String number = "1000500000.574";
Double numParsed = Double.parseDouble(number);
System.out.println(String.format("The input number is: %,.2f", numParsed));
// Or
String numString = String.format("%,.2f", numParsed);
For the format string "%,.2f" - "," means separate digit groups with commas, and ".2" means round to two places after the decimal.
For reference on other formatting options, see https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
Given this is the number one Google result for format number commas java, here's an answer that works for people who are working with whole numbers and don't care about decimals.
String.format("%,d", 2000000)
outputs:
2,000,000
Once you've converted your String to a number, you can use
// format the number for the default locale
NumberFormat.getInstance().format(num)
or
// format the number for a particular locale
NumberFormat.getInstance(locale).format(num)
I've created my own formatting utility. Which is extremely fast at processing the formatting along with giving you many features :)
It supports:
Comma Formatting E.g. 1234567 becomes 1,234,567.
Prefixing with "Thousand(K),Million(M),Billion(B),Trillion(T)".
Precision of 0 through 15.
Precision re-sizing (Means if you want 6 digit precision, but only have 3 available digits it forces it to 3).
Prefix lowering (Means if the prefix you choose is too large it lowers it to a more suitable prefix).
The code can be found here. You call it like this:
public static void main(String[])
{
int settings = ValueFormat.COMMAS | ValueFormat.PRECISION(2) | ValueFormat.MILLIONS;
String formatted = ValueFormat.format(1234567, settings);
}
I should also point out this doesn't handle decimal support, but is very useful for integer values. The above example would show "1.23M" as the output. I could probably add decimal support maybe, but didn't see too much use for it since then I might as well merge this into a BigInteger type of class that handles compressed char[] arrays for math computations.
you can also use the below solution
public static String getRoundOffValue(double value){
DecimalFormat df = new DecimalFormat("##,##,##,##,##,##,##0.00");
return df.format(value);
}
public void convert(int s)
{
System.out.println(NumberFormat.getNumberInstance(Locale.US).format(s));
}
public static void main(String args[])
{
LocalEx n=new LocalEx();
n.convert(10000);
}
You can do the entire conversion in one line, using the following code:
String number = "1000500000.574";
String convertedString = new DecimalFormat("#,###.##").format(Double.parseDouble(number));
The last two # signs in the DecimalFormat constructor can also be 0s. Either way works.
Here is the simplest way to get there:
String number = "10987655.876";
double result = Double.parseDouble(number);
System.out.println(String.format("%,.2f",result));
output:
10,987,655.88
The first answer works very well, but for ZERO / 0 it will format as .00
Hence the format #,##0.00 is working well for me.
Always test different numbers such as 0 / 100 / 2334.30 and negative numbers before deploying to production system.
According to chartGPT
Using DecimalFormat:
DecimalFormat df = new DecimalFormat("#,###.00");
String formattedNumber = df.format(yourNumber);
Using NumberFormat:
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setGroupingUsed(true);
String formattedNumber = nf.format(yourNumber);
Using String.format():
String formattedNumber = String.format("%,.2f", yourNumber);
Note: In all the above examples, "yourNumber" is the double value that you want to format with a comma. The ".2f" in the format string indicates that the decimal places should be rounded to 2 decimal places. You can adjust this value as needed.