How to get formatted currency value for India? - java

For example in USA 1000000 represented as 1,000,000 (1 million) but in India it is represented as 10,00,000 (10 lakh). For this I tried some methods
double value = 1000000d;
NumberFormat numberFormatter = NumberFormat.getNumberInstance(new Locale("en", "IN"));
System.out.println(numberFormatter.format(value));
NumberFormat deci = new DecimalFormat("#,##,##,###.##");
System.out.println("Decimal Format "+deci.format(value));
NumberFormat format = NumberFormat.getNumberInstance();
format.setCurrency(Currency.getInstance("INR"));
format.setMaximumFractionDigits(2);
System.out.println(format.format(value));
But all these methods give an output as 1,000,000 but I require format 10,00,000. What do I need to change here?

Java decimal formatter doesn't support groups From Docs :
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 "#,##,###,####" ==
"######,####" == "##,####,####".
You will need another library for this. Suggest this :
http://site.icu-project.org/
https://mvnrepository.com/artifact/com.ibm.icu/icu4j/69.1
Code
double value = 1000000d;
NumberFormat numberFormatter = NumberFormat.getNumberInstance(new Locale("en", "IN"));
System.out.println(numberFormatter.format(value));
Output :
10,00,000

public static String fmt(String s)
{
String formatted = "";
if(s.length() > 1){
formatted = s.substring(0,1);
s = s.substring(1);
}
while(s.length() > 3){
formatted += "," + s.substring(0,2);
s = s.substring(2);
}
return formatted + "," + s + ".00";
}

Related

How can i make a Number Format Like 000"+"000 in android

I want to make a number format like 000"+"000. The rule will be 3 digits "+" 3 digits. I will give you some examples below.
I have tried some codes before i will show them below. I think i have to use NumberFormat class. My codes are below. by the way my number maximum have 6 digits if number has less digits the missing digits(which will be in left), has to be 0.
I tried
NumberFormat numberFormat = new DecimalFormat("000'+'000");
but it gave error which is
Unquoted special character '0' in pattern "000'+'000"
but it was worked when i make
NumberFormat numberFormat = new DecimalFormat("'+'000");
or
NumberFormat numberFormat = new DecimalFormat("000'+'");
So simply i can make number-plus or plus-number but i can't make number(3 digit)-plus-number(3 digit)
I expect to get these outputs for these inputs:
input: 4032
output: 004+032
input : 5
output: 000+005
input: 123450
output: 123+450
input: 10450
output: 010+450
With a trick: change the grouping separator symbol to +:
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault());
symbols.setGroupingSeparator('+');
NumberFormat nf = new DecimalFormat("000,000", symbols);
int x = 3250;
System.out.println(nf.format(x));
Result:
003+250
Or use a method like this:
public static String specialFormat(int number) {
NumberFormat nf = new DecimalFormat("000");
return nf.format(number / 1000) + "+" + nf.format(number % 1000);
}
it formats separately the 3 first digits and the 3 last digits and concatenates with a + in the middle.
Use it:
int x = 5023;
System.out.println(specialFormat(x));
Result:
005+023
What you want is not a decimal syntax. Therefor, you cannot use the DecimalFormat, because it handles all kinds of localized numbers but not arbitrary ones like yours. However, you might want to implement your own java.text.Format.
What about using this kind of method and later convert it to the format you want
generateNumbers(String val) {
int len = val.length();
String finalValue;
StringBuffer sb = new StringBuffer();
if (len < 6) {
for (int i = 6; i > len; i--) {
sb.append("0");
}
finalValue = sb.append(val).toString();
} else {
finalValue = val;
}
System.out.println(finalValue.substring(0, 3) + "+" + finalValue.substring(3));
}
for testing you can call this
generateNumbers("4032");
generateNumbers("5");
generateNumbers("123450");
generateNumbers("10450");
Output is
004+032
000+005
123+450
010+450
Let me know if it's useful.

How to convert Double to String with exponential sign

I want to convert a Double to String with exponential signs in it.
For example, Double value is 4.4395749E7 after converting to String it should be 4.4395749E+07 (Same as how it shows in MS Excel).
I have tried double.toString(), but it is converting to 4.4395749E7:
Double doubleValue = 44395749d;
doubleValue.toString();
Expected is 4.4395749E+07, but actual is 4.4395749E7.
you can use String.format(), E is the format code for exponentials
Double doubleValue = 44395749d;
System.out.println(String.format("%E", doubleValue));
You can use DecimalFormat to format your number:
Double value = 44395749d;
DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
if (value > 1 || value < -1) {
symbols.setExponentSeparator("E+");
}
DecimalFormat decimalFormat = new DecimalFormat("0E00", symbols);
decimalFormat.setMaximumFractionDigits(Integer.MAX_VALUE);
System.out.println(decimalFormat.format(value));
This uses DecimalFormatSymbols to add the + for the exponent if needed (value > 1 or value < -1). To get all fraction digits use setMaximumFractionDigits(Integer.MAX_VALUE). You can simply change the format if needed.
The result will be 4.4395749E+07.
Bare in mind to set a specific locale if needed:
DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(Locale.ENGLISH)

java: get different parts of NumberFormat.getCurrencyInstance() result

In Java, with NumberFormat.getCurrencyInstance(), I can get a formatted string representing a price. e.g.
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.GERMANY);
System.out.println(nf.format(20.10)); // "20,10 €"
Is there an easy way to get the different part of this formatted string? i.e. something like
integerPart -> 20
decimalPart -> 10
currencySymbol -> €
decimalSeparator -> ,
Thanks!
You're really asking for two separate things:
integerPart and decimalPart belong to the input value. They can be calculated with some simple math:
double input = 20.10;
int integerPart = (int)input; // 20
int decimalPart = (int)((input - integerPart) * 100); // 10
currencySymbol and decimalSeparator relate to the output value. They can be retrieved using the DecimalFormatSymbols class:
DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(Locale.GERMANY);
String currencySymbol = symbols.getCurrencySymbol(); // €
char decimalSeparator = symbols.getDecimalSeparator(); // ,

How to format a double into thousand separated and 2 decimals using java.util.Formatter

I want to format a double value into a style of having
Currency Format Symbol
Value rounded into 2 decimal places
Final Value with thousand separator
Specifically using the java.util.Formatter class
Example :-
double amount = 5896324555.59235328;
String finalAmount = "";
// Some coding
System.out.println("Amount is - " + finalAmount);
Should be like :-
Amount is - $ 5,896,324,555.60
I searched, but I couldn't understand the Oracle documentations or other tutorials a lot, and I found this link which is very close to my requirement but it's not in Java -
How to format double value into string with 2 decimal places after dot and with separators of thousands?
If you need to use the java.util.Formatter, this will work:
double amount = 5896324555.59235328;
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("$ %(,.2f", amount);
System.out.println("Amount is - " + sb);
Expanded on the sample code from the Formatter page.
You could use printf and a format specification like
double amount = 5896324555.59235328;
System.out.printf("Amount is - $%,.2f", amount);
Output is
Amount is - $5,896,324,555.59
To round up to 60 cents, you'd need 59.5 cents (or more).
Instead of using java.util.Formatter, I would strongly suggest using java.text.NumberFormat, which comes with a built-in currency formatter:
double amount = 5896324555.59235328;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String finalAmount = formatter.format(amount);
System.out.println("Amount is - " + finalAmount);
// prints: Amount is - $5,896,324,555.59

How not to get a comma on the output?

NumberFormat df = NumberFormat.getNumberInstance();
df.setMaximumFractionDigits (2);
df.setMinimumFractionDigits (2);
double[] floatValues = new double[5];
String Input;
Input = stdin.readLine();
String[] floatValue = Input.split("\\s+");
while (letter != 'q' && letter != 'Q'){
for (int i = 0; i < floatValue.length; ++i){
floatValues[i] = Double.parseDouble (floatValue[i]);
System.out.println("LWL:" + df.format((floatValues[1])));
System.out.println("Hull Speed:" + df.format(1.34 * Math.sqrt(floatValues[1])));
This is part of the code, I'm suppose to input 5 numbers like: 34.5 24.0 10.2 11200 483. My program runs perfectly, the only problem is that the output is suppose to be 11200 and I get 11,200. How do I get it to not output the comma. Thank You.
This is the issue:
NumberFormat df = NumberFormat.getNumberInstance();
That's getting the format for your machine's default locale, which presumably uses a comma as the decimal point. Just use the US locale:
NumberFormat df = NumberFormat.getNumberInstance(Locale.US);
That will then use a dot for the decimal point regardless of your machine's locale.
Call df.setGroupingUsed(false).
From java.text.NumberFormat.isGroupingUsed():
Returns true if grouping is used in this format. For example, in the English locale, with grouping on, the number 1234567 might be formatted as "1,234,567". The grouping separator as well as the size of each group is locale dependant and is determined by sub-classes of NumberFormat.
This will result in the output "11200.00". If you really want "11200", i.e. no fraction digits (contrary to your code), call df.setMaximumFractionDigits(0) and discard df.setMinimumFractionDigits(2).

Categories