I am trying to convert an input string to euro/Bulgarian currency,I am having two scenario's.
First,
When input is 10,000 the Bulgarian format should be like 10 000 and euro format should be 10.000
Second,
if the input is 10.23 then both European and Bulgarian format should be 10,23.
I am trying to do using Big Decimal,Something like,
String s = "+000000055511.00";
BigDecimal b = new BigDecimal(s.replace(",", "."));
b.setScale(2, RoundingMode.HALF_UP);
System.out.println(b.toPlainString());
But I am not able to do it as an common utility which takes and converts into euro or bulgarian currency.Is there any utility for the same?Can somebody help me?
You may use java.text.NumberFormat.getCurrencyInstance(Locale) with appropriate locals. If there are no such locals which match your requirements then construct your own decimal formatter java.text.DecimalFormat with pattern ##' '##0.00 resp. ##,##0.00 plus appropriate currency sign. The formatter can be applied to BigDecimal:
String s = "+000000027511.00";
BigDecimal B = new BigDecimal(s);
// don't replace "." by ",": english number format expected here
b.setScale(2, RoundingMode.HALF_UP);
NumberFormat f = new DecimalFormat(...); //initialize as requested see docs
System.out.println(f.format(b));
Another question is why you don't want fraction digits if your number is 10,000? If this is really the case you must define two formatters more and must select them according to your creteria.
Hope this helps.
Related
I am trying to make a number in a BigDecimal variable match the format of ###.# where no matter what number is passed it will come out as ###.#
For example, if I was passed the number 1 in a BigDecimal variable the method would return 001.0
If I was passed 11.1 as a BigDecimal variable the method would return 011.1
I already have a bit of the code to make the decimal places match
BigDecimal x = new BigDecimal(1);
DecimalFormat df = new DecimalFormat("#.0");
String formatted = df.format(x);
So this would return 1.0 however I cannot figure out how to make the leading zeros appear before converting back to BigDecimal.
Can someone help me out or point me in the right direction?
Thanks everyone
Use a NumberFormat instance, with a Locale which uses the dot as decimal separator.
final BigDecimal x = new BigDecimal("11.1");
final NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
nf.setMinimumFractionDigits(1);
nf.setMaximumFractionDigits(1);
nf.setMinimumIntegerDigits(3);
final String formatted = nf.format(x);
NumberFormat is basically a Factory, so for example in this case the underlying formatter returned by getNumberInstance is a DecimalFormat. I always prefer being abstracted off the real implementation.
You can also decide if you want to display the grouping comma or not.
nf.setGroupingUsed(true); // 123,456.0 - default value is true
nf.setGroupingUsed(false); // 123456.0
Use new DecimalFormat("000.0")
Examples
DecimalFormat df = new DecimalFormat("000.0", DecimalFormatSymbols.getInstance(Locale.US));
System.out.println(df.format(new BigDecimal("1"))); // prints: 001.0
System.out.println(df.format(new BigDecimal("11.1"))); // prints: 011.1
System.out.println(df.format(new BigDecimal("123.456"))); // prints: 123.5
System.out.println(df.format(new BigDecimal(".07"))); // prints: 000.1
System.out.println(df.format(new BigDecimal("123456"))); // prints: 123456.0
You can use the StringUtils of apache.
StringUtils.leftPad(number.toString(), 3, '0');
Where the first argument is the String to format, second argument is the number of to left places to validate, and the last argument is the char for complete.
Reggards.
I do have some numbers like 100,000 and I want output as 1 Lakh in Indian numbering system. is there any method that supports it?
Detailed Example.
Input 5,50,000
Output 5.5 Lakh
You could try stripping the commas, casting to an integer, the dividing to get the number of Lakhs:
DecimalFormat df = new DecimalFormat("#.#####");
String input = "5,50,000";
double lakhs = Double.parseDouble(input.replaceAll(",", "")) / 100000;
String out = df.format(lakhs);
System.out.println(out);
Demo
You can use this github library:
https://github.com/fabiomsr/MoneyTextView
That is display amounts of money in different formats.
i was made this method to show value of int into text view
texton= (TextView)findViewById(R.id.textcolumn);
texton.setText(String.valueOf(score));
so it will show like this
but i want to make the number text format like this, it is possible?
You can use DecimalFormat .
public class DecimalFormat extends NumberFormat
DecimalFormat is a concrete subclass of NumberFormat that formats
decimal numbers. It has a variety of features designed to make it
possible to parse and format numbers in any locale, including support
for Western, Arabic, and Indic digits. It also supports different
kinds of numbers, including integers (123), fixed-point numbers
(123.4), scientific notation (1.23E4), percentages (12%), and currency
amounts ($123). All of these can be localized.
Please have a look here
NumberFormat
How can I format a String number to have commas and round?
So Try this way ,
DecimalFormat formatter = new DecimalFormat("#,###.000");
String get_value = formatter.format(score);
texton= (TextView)findViewById(R.id.textcolumn);
texton.setText(get_value);
Logic Courtesy
You can use DecimalFormat before setting the value in textView
texton.setText(setDotsDigit(score));
public static String setDotsDigit(double value)
{
return new DecimalFormat("###.###.###").format(value);
}
You should use DecimalFormat to format your score value first.
DecimalFormat formatter = new DecimalFormat("#,###.00")`;
String s = formatter.format(score);
texton = (TextView)findViewById(R.id.textcolumn);
texton.setText(s);
Hope it will help you.
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("[-,]", "");
Good day.
I need to format a number in java.
So far I have this:
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
System.out.println(new Double(df2.format(balance)).doubleValue());
But it prints out this
110.0
121.0
133.1
146.41
161.05
But I need it to be with two digits in fraction part. How do I do it?
You don't have to get double value from formatted string.
Just use formatted string, which is returned from format() method of DecimalFormat.
So your code should be like the following:
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
...
System.out.println(df2.format(balance));
Your original code:
System.out.println(new Double(df2.format(balance)).doubleValue());
What you did in your code is: format the double value to string(which is formatted as you specified in the DecimalFormat instance). Then you convert the formatted string to Double instance and get double value from the object, which is double. And then printed it to console. So the formatted string is gone, and the double value is printed as normal.
"But I need it to be with two digits in fraction part. How do I do it?"
DecimalFormat df2 = new DecimalFormat( );
df2.setMinimumFractionDigits(2);
df2.setMaximumFractionDigits(2);
System.out.println(df2.format(balance));
You could also use the setMinimumFractionDigits method of DecimalFormat
df2.setMinimumFractionDigits(2);
your decimal format is right, but
what you are doing before you print this out is new Double(df2.format(balance)) which create new instant of double, which ignores your formatting.
so if you want to display or log your value df2.format(balance) this should be enough
ie:
System.out.println(df2.format(balance));
Try this pattern for formatting #,###,###,##.##-
DecimalFormat df2 = new DecimalFormat( "#,###,###,##.##" );
System.out.println(df2.format(balance));
This should be sufficient:
DecimalFormat df2 = new DecimalFormat("#,##0.00");
System.out.println(df2.format(balance));
The grouping for separator will follow "the interval between the last one and the end of the integer". So there is no benefit from over-specify. Example from the documentation of DecimalFormat:
The grouping separator is commonly used for thousands, but in some countries it separates ten-thousands. The grouping size is a constant number of digits between the grouping characters, such as 3 for 100,000,000 or 4 for 1,0000,0000. If you supply a pattern with multiple grouping characters, the interval between the last one and the end of the integer is the one that is used. So "#,##,###,####" == "######,####" == "##,####,####".
Another thing is that .format() method already output a String, so there is no point in converting it to double. It will cause Exception to be thrown when balance is more than 1000 (the point when separator comes into effect, and Double class cannot parse the String with separator).