I'm trying to format a BigDecimal value by using methods of DecimalFormat.format().
My problem, is I don't know how to set DecimalFormats DecimalFormatSymbol to format text without any grouping separators.
I'd like to know how to set a grouping symbol and use the format methods. I know how to do it differently by using replace or others methods but it's not what I want.
So I need to know how to set an empty character as grouping operator.
Example:
DecimalFormat dec = new DecimalFormat();
DecimalFormatSymbols decFS = new DecimalFormatSymbols();
decFS.setGroupingSeparator( '\0' );
dec.setDecimalFormatSymbols( decFS );
BigDecimal number = new BigDecimal(1000);
String result = dec.format(number);
I want to get "1000" as string with no other characters. Please help
note(react to post): I want to formate the number only, without grouping.
Simply:
DecimalFormat dec = new DecimalFormat();
dec.setGroupingUsed(false);
If you dont want any formatting marks in the number you should just call toString on the BigDecimal Object.
import java.math.*;
public class TestBigDecimal
{
public static void main(String[] args)
{
BigDecimal number = new BigDecimal(1000);
String result = number.toString();
}
}
String result = String.valueOf(number);
returns your number as a string with no formatting.
Related
I want to convert double value up to two decimals. It is working fine for values like 6779.77,22334.22 but it doesn't work for value 33445.90,3334.30 it shows only 33445.9 and 3334.3 values does not show 0.
Why is it so?
public static String formatAmount(String number) {
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,##,##,###.##");
return formatter.format(amount);
}
# means that trailing zeroes can be omitted. Instead, you should use the 0 format character:
DecimalFormat formatter = new DecimalFormat("#,##,##,###.00");
// Here -------------------------------------------------^
I was wondering if there is an existing method to convert a formatted number String to number, such as "123,456.78" to 123456.78
Basically, unlike DecimalFormat function, which turns a double variable to a String following that a given format such as "###,###.##" pattern. I want to implement a reverse of this functionality, which turns a String with "###,###.##" format to a double. Is there APIs to do this?
Thank you.
You should have looked through the documentation for DecimalFormat and its superclass. You would have discovered that it has not only format methods, but also parse methods like this one.
The easiest way to do what you want is:
NumberFormat format = NumberFormat.getInstance();
Number value = format.parse(string);
// If you specifically want a double...
double d = value.doubleValue();
You will have to catch ParseException and deal with it. How you do that depends on what you want to do when your string does not represent a valid numeric value. If it's user input, you may want to ask the user to enter the text again.
Here is a simple way to do this
String number = "20,000,000";
int x = Integer.parseInt(number.replace(",", ""));
System.out.println(x);
You just replace the char's that not belong to a number with "" and then parse it into a primitive.
String number = "20,000,000.56";
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(5);
double x = Double.parseDouble(number.replace(",", ""));
System.out.println(df.format(x));
It is a bit different for a Double cause it will display the exponential output and you'll have to prevent that. The code above does that.
df.format(x)
Returns a String but you can cast it with the Double.parseDouble method
Here's a method using a Regex and the replace method if you have more than one delimiter and you know them all :
Let's say the delimiters here are "-" and ","
double x = Double.parseDouble(number.replace("[-,]", "");
I'd like to use String.format() to format some BigDecimals as part of a string:
// Example:
String getPrice( String pattern )
{
BigDecimal price = basePrice.multiply( BigDecimal.ONE.add( vatRate ) );
BigDecimal priceInPence = price.multiply( new BigDecimal( "100" ) );
BigDecimal annualPrice = price.multiply( new BigDecimal( "365" ) );
return String.format( pattern, priceInPence, annualPrice );
}
String myPrice1 = getPrice( "Your price is %1$.3fp/day (£2$.2f/year) including VAT" );
// --> "Your price is 32.100p/day (£117.16/year) including VAT"
String myPrice2 = getPrice( "Around £%2$.0f annualy" );
// --> "Around £117 annually"
However the docs for String.format() say that any rounding of BigDecimals will be done with HALF_UP rounding, whereas I need HALF_EVEN.
I know how to manually set the scale of BigDecimals (Set specific precision of a BigDecimal) - but in this case I want to be able to use an arbitrary pattern string (including non-numeric pattern elements), so I won't know in advance what scale to use.
My question is therefore:
can I set the rounding mode used by String.format()? OR
is there another formatter or library that would format the numbers as in my example?
can I set the rounding mode used by String.format()?
Short answer: no.
is there another formatter or library that would format the numbers as in my example?
The BigDecimal is converted internally via new MathContext(compPrec) or plain HALF_UP.
You can take the code of java.util.Formatter of the latest (or your preferred) version Java and modify the creation of the MathContext to use HALF_EVEN. It should be 10-15minutes work. But then you need a custom method to mimic String.format:
public static String format(String format, Object... args) {
return new FormatterHALF_EVEN().format(format, args).toString();
}
Really "solid" advice to add 5000 lines of dead-weight code to your project! From what I see, the Formatter will not set scale unless it is already set to what is needed. So help it out, parse the format string and set your scale:
public static String getPrice(String pattern) {
BigDecimal basePrice = new BigDecimal("23");
BigDecimal vatRate = new BigDecimal("0.5");
BigDecimal price = basePrice.multiply(BigDecimal.ONE.add(vatRate));
BigDecimal priceInPence = price.multiply(new BigDecimal("100"));
BigDecimal annualPrice = price.multiply(new BigDecimal("365"));
Matcher matcher = Pattern.compile("%(\\d+)\\$.(\\d+)f").matcher(pattern);
while (matcher.find()) {
String index = matcher.group(1);
int scale = Integer.parseInt(matcher.group(2));
if (index.equals("1"))
priceInPence = priceInPence.setScale(scale, RoundingMode.HALF_EVEN);
else if (index.equals("2"))
annualPrice = annualPrice.setScale(scale, RoundingMode.HALF_EVEN);
}
return String.format(pattern, priceInPence, annualPrice);
}
with these numbers I get this output:
Your price is 3450.000p/day (£12592.50/year) including VAT
Around £12592 annualy
So it applies correct rounding.
Set the scale with the rounding mode you like, and include the values in the format string as strings, using BigDecimal#toString().
is there a class in Java that lets you format a number like "102203345.32" to this "102.203.345,32" and return a string type?
I would like to obtain a String where the thousands are separated by the '.' and the decimals are separated by a comma ','.
Could someone help me please? I found a class DecimalFormat and I tried to customize it:
public class CustomDecimalFormat {
static public String customFormat(String pattern, double value ) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
return output;
}
}
but when I call the customFormat method like this: CustomDecimalFormat.customFormat("###.###,00") I get an exception...
What should I do?
Thanks!
Be sure to read and understand the Special Pattern Characters section of the Javadoc, especially this note:
The characters listed here are used in non-localized patterns. Localized patterns use the corresponding characters taken from this formatter's DecimalFormatSymbols object instead, and these characters lose their special status.
If you have done that, it should be clear to you that you must use the appropriate constructor and supply the appropriately configured separator/grouping chars, whereas in the pattern itself the dot and the comma have a special meaning.
All the complexity above is there for your convenience, actually: it allows you to customize the number format and have it localized.
Here's a code sample which worked for me:
final DecimalFormatSymbols syms = new DecimalFormatSymbols();
syms.setDecimalSeparator(',');
syms.setGroupingSeparator('.');
DecimalFormat myFormatter = new DecimalFormat("###,###.00", syms);
System.out.println(myFormatter.format(1234.12));
You can also use a variant where you apply the localized pattern, for more intuitive code:
final DecimalFormatSymbols syms = new DecimalFormatSymbols();
syms.setDecimalSeparator(',');
syms.setGroupingSeparator('.');
DecimalFormat myFormatter = new DecimalFormat("", syms);
myFormatter.applyLocalizedPattern("###.###,00");
System.out.println(myFormatter.format(1234.12));
First of all,
you misplaced the comma and decimal points. Your format should be : ###,###.00 instead of ###.###,00 ...
Also check with your Locale, it has an effect on the format. See the link below.
http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
You can try GERMAN number format
NumberFormat.getNumberInstance(Locale.GERMAN).format(102203345.32)
I would like to format an amount : the required format is : #.##0,00
example : 299.552.698,05 or 299.552.698,00
When I try to use
(new DecimalFormat("#.##0,00")).format($F{amount}.doubleValue())
It causes an exception and whan I try to use :
NumberFormat.getCurrencyInstance(Locale.ENGLISH).format($F{amount}.doubleValue())
I have the symbole of the currency which I don't want to print.
"#.##0,00" is an invalid format string.
The comma, and only the comma, is the grouping character, but it is localized, meaning if you set the Locale, you'll get the appropriate separator for your locale.
If you prefer the "one-line hack" way, this will work:
new DecimalFormat("#,##0.00").format($F{amount}.doubleValue()).replace(",", "x").replace(".", ",").replace("x", ".");
Well, I would use the DecimalFormatSymbols class to trick the formatter, like this:
public String formatNumber(double value) {
DecimalFormat formatter = new DecimalFormat("###,###.00");
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault());
symbols.setDecimalSeparator(',');
symbols.setGroupingSeparator('.');
formatter.setDecimalFormatSymbols(symbols);
return formatter.format(value);
}
hope it works for you...
Maybe something like:
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH);
return (new DecimalFormat("#.##0,00", symbols)).format($F{amount}.doubleValue());
Check out the two argument constructor for DecimalFormat