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

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(); // ,

Related

How to get formatted currency value for India?

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";
}

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.

Remove Decimals from String

I have a function that converst a BigDecimal into a String plus the currency. When I use this the number (e.g. 34) turns into a number with a lot of decimals (e.g. 34.000000).
What can I do to solve this and just show the 34?
Here is my function:
row.put("Money", GcomNullPointerValidator.isNullField(formatUtils.formatCurrency(MoneyDto.getAmount().stripTrailingZeros())));
What is the language? Java?
You can use the split() function of String if you just want to keep numbers before "." :
String mystring = "34.000000";
String correctstring[] = mystring.split(".");
System.out.println(correctstring[0]);
// display : 34
it will delete all digits after "." !
Inside your method that converts a BigDecimal into a String, you can use BigDecimal.setScale() to set the number of digits after the decimal point. For example:
BigDecimal d = new BigDecimal("34.000000");
BigDecimal d1 = d.setScale(2, BigDecimal.ROUND_HALF_UP); // yields 34.00
BigDecimal d2 = d.setScale(0, BigDecimal.ROUND_HALF_UP); // yields 34
You can use this:
String number = "150.000";
number.replaceAll("\\.\\d+$", "");
Or you can use this:
number.split(Pattern.quote("."))[0];

Java: Lead 0 in double and 1 digit after a dot

I want to format a double to string with the max length is 7 which contains a dot "." and one digit after it.
For example:
123.4 becomes "00123.4"
12345 becomes "12345.0"
12345.63 becomes "12345.6"
Any help, please!
you can do this:
double test = 33333.327;
String formatted = String.format("%07.1f", test)
System.out.println(formatted);
String.format("%07.1f", myDouble);
See http://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html
Try this -
DecimalFormat df = new DecimalFormat("00000.0");
...
System.out.println(df.format(123.4)); -> 00123.4
System.out.println(df.format(12345)); -> 12345.0
System.out.println(df.format(12345.63)); -> 12345.6

Print rounded digits without extra zeros

I'm trying to round using BigDecimal.ROUND_HALF_UP but am not getting expected results. This code:
String desVal="21.999";
BigDecimal decTest=new BigDecimal(
String.valueOf(desVal)
)
.setScale(
Integer.parseInt(decimalPlaces), BigDecimal.ROUND_DOWN
);
System.out.println(decTest);
Gives the following results:
decimalPlaces=1 it is displaying 21.9 //correct
decimalPlaces=2 displaying 21.99 //correct
decimalplaces=3 displaying 21.999 //correct
decimalplaces=4 displaying 21.9990 //incorrect
I want to get the following:
decimalPlaces=1 should display 21.9
decimalPlaces=2 should display 21.99
decimalplaces=3 should display 21.999
decimalplaces=4 should display 21.999
Is there a way to do this with standard Java (ie no external libraries)?
Use BigDecimal#stripTrailingZeros():
String[] decimalPlaces = new String[] {"2", "2", "3", "4", "4"};
String[] desVal = new String[] {"20", "21.9", "21.90", "21.99999", "21.99990"};
for (int i = 0; i < desVal.length; i++) {
BigDecimal decTest = new BigDecimal(desVal[i]);
if (decTest.scale() > 0 && !desVal[i].endsWith("0") && !(Integer.parseInt(decimalPlaces[i]) > decTest.scale())) {
decTest = decTest.setScale(Integer.parseInt(decimalPlaces[i]),
BigDecimal.ROUND_DOWN).stripTrailingZeros();
}
System.out.println(decTest);
}
Output:
20
21.9
21.90
21.9999
21.99990
int decPlaces = Math.min(Integer.parseInt(decimalPlaces),
desVal.length() - desVal.indexOf(".") + 1);
BigDecimal decTest=
new BigDecimal(String.valueOf(desVal)).
setScale(decPlaces, BigDecimal.ROUND_DOWN);
You can use java.text.NumberFormat
NumberFormat nf = NumberFormat.getInstance();
System.out.println(nf.format(decTest));
If you want to preserve original scale, then
String desVal="21.99901";
BigDecimal decTest=new BigDecimal(String.valueOf(desVal));
int origScale = decTest.scale();
decTest = decTest.setScale(4, BigDecimal.ROUND_DOWN);
System.out.println(String.format("%."+origScale+"f", decTest));
If you want to print trailing zeroes, but not all of them, you will need a DecimalFormat.
The trick is that in your case, you need to build the Format String depending on the number of decimals in the original input String.
int decimalPlaces = 10;
String desVal="21.99900";
// find the decimal part of the input (if there is any)
String decimalPart = desVal.contains(".")?desVal.split(Pattern.quote("."))[1]:"";
// build our format string, with the expected number of digits after the point
StringBuilder format = new StringBuilder("#");
if (decimalPlaces>0) format.append(".");
for(int i=0; i<decimalPlaces; i++){
// if we've passed the original decimal part, we don't want trailing zeroes
format.append(i>=decimalPart.length()?"#":"0");
}
// do the rounding
BigDecimal decTest=new BigDecimal(
String.valueOf(desVal)
)
.setScale(
decimalPlaces, BigDecimal.ROUND_DOWN
);
NumberFormat nf = new DecimalFormat(format.toString());
System.out.println(nf.format(decTest));

Categories