Java: altering locale formatting - java

I would like to modify the way my application locale formats and displays numbers.
In my case the locale is "it_IT", so numbers are formatted with '.' as GroupingSeparator and ',' as DecimalSeparator. Is it possible to alter or remove those symbols at global application level?

Depending on what do you want there a different ways. See some below...
1 set the default locale in your applicationLocale.setDefault(Locale.UK); this will use a comma as GroupingSeparator and a point as DecimalSeparator
2 you can create the java.text.NumberFormat for a specific locale NumberFormat.getInstance(Locale.UK), will behave like solution 1)
3 you can use one of the above an remove the GroupingSeparator
NumberFormat formatUK = NumberFormat.getInstance(Locale.UK);
formatUK.setGroupingUsed(false);
edit:
import java.text.NumberFormat;
import java.util.Locale;
public class Foo {
public static void main(String[] args) {
NumberFormat formatUK = NumberFormat.getInstance(Locale.UK);
double someValue = 1234567.8899;
System.out.printf("%16s: %15s%n", "with grouping", formatUK.format(someValue));
formatUK.setGroupingUsed(false);
System.out.printf("%16s: %15s%n", "without grouping", formatUK.format(someValue));
}
}

Related

How to use decimal number without creating a String resource

In Java and Kotlin there is an API that can used to show a time without having to create a string resource.
In the example line of code below, this value allows the time of 8 hours after midnight to automatically chnage the way its displayed depending on the device locale.
val timeCustom = LocalTime.of(8, 0)
Is there something similar that can be used for a decimal number, where the value automatically uses a specific demical symbol dpending on the locale? (. or ,).
For example, to describe the height of something (e.g. 5 point 2 metres):
val decimalNumber = Decimal.of(5,2)
Is there something like this available?
You can use Locale.getDefault() e.g.
import java.text.NumberFormat;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Locale currentLocale = Locale.getDefault();
Integer quantity = 123456;
Double amount = 345987.246;
NumberFormat numberFormatter;
String quantityOut;
String amountOut;
numberFormatter = NumberFormat.getNumberInstance(currentLocale);
quantityOut = numberFormatter.format(quantity);
amountOut = numberFormatter.format(amount);
System.out.println(quantityOut);
System.out.println(amountOut);
}
}
Output:
123,456
345,987.246

How can i format turkish lira with symbol?

I tried to do it with the locale, but it only appears as text and the symbol doesn't come out. I am using JAVA 14 SDK.
Code I tried:
Locale tr = new Locale("tr", "TR");
BigDecimal points = new BigDecimal(175678.64);
System.out.println(NumberFormat.getCurrencyInstance(tr).format(points));
Output:
175.678,64 TL
I want:
₺175.678,64
No problem
I broke out your code to multiple lines for easier debugging.
When I run it in the IdeOne.com site, I get your desired output.
By the way, you should pass your input number as text (add quote marks). Otherwise you are defeating the purpose of using BigDecimal.
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.* ;
import java.text.* ;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Locale locale = new Locale("tr", "TR");
BigDecimal points = new BigDecimal( "175678.64" ) ;
NumberFormat f = NumberFormat.getCurrencyInstance( locale ) ;
String output = f.format( points ) ;
System.out.println( output ) ;
}
}
When run:
₺175.678,64
Consider using the Currency class of java.util.Currency.
The Currency class has two methods getSymbol() and getSymbol(Locale locale). In your case you should use the second method with the locale parameter. This will return a String that represents the currency symbol for turkish lira.
You can initialize your Currency object like this:
Currency currency = Currency.getInstance(tr);
and
currency.getSymbol(tr);
will return the currency symbol as a String
In addition, you should know that the unidoce representation of turkish lira symbol as a char in Java is \u20BA
try this change 'Locale.CANADA' with your country
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.CANADA);
String currency = format.format(number);
System.out.println("Currency in Canada : " + currency);

How to format 6 or 9 digit number like #,##,###

How to format 6 or 9 digit number like #,##,### [for 6] and ##,##,##,### [for 9]
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class CheckFormater {
public static void main(String[] args) {
NumberFormat nf6 = new DecimalFormat("#,##,###");
System.out.println(nf6.format(123456d));
NumberFormat nf9 = new DecimalFormat("##,##,##,###");
System.out.println(nf9.format(123456789d));
}
}
I am getting output as follows
123,456
123,456,789
I am expecting as follows
1,23,456
12,34,56,789
How to do costume formatting ?
You can use ICU4J
import com.ibm.icu.text.DecimalFormat;
import com.ibm.icu.text.DecimalFormatSymbols;
public class NewClass {
public static void main(String[] args) {
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setGroupingSeparator(',');
DecimalFormat nf6 = new DecimalFormat("#,##,###", dfs);
DecimalFormat nf9 = new DecimalFormat("##,##,##,###", dfs);
System.out.println(nf6.format(123456d));
System.out.println(nf9.format(123456789d));
}
}
//prints
//1,23,456
//12,34,56,789
Here is what Java Docs say:
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 "#,##,###,####" == "######,####" == "##,####,####".
So in other words, you can only specify one grouping separator format at a time. Either a thousands separator or ten thousand separator or hundred separator. Even if you try to specify multiple formats in one, the method will use only the interval between the last one and the end of the integer. So in your case you are specifying "#,##,###" but the method will consider only the last comma and the number of digits afterwards which is 3 in your case. That's why the output is a thousand separator.
I was also hoping that selecting a proper locale should address this number formatting issue without needing to specify any pattern. E.g. in India, the numbers are in fact formatted the way you want. The first separator is thousand digit based and the rests are hundred digit based. So if I select Indian English locale, it should automatically address this requirement. But it doesn't.
NumberFormat nf6 = NumberFormat.getInstance(new Locale("en-IN"));
System.out.println(nf6.format(54123756.523d));//Still prints 54,123,756.523 and not 5,41,23,756.523
So unfortunately there is no ready made way to achieve your objective unless you go for the recommendation of using third party libraries in the other answer. However you can always use a heck. It is not neat but achieves the objective. Maybe you can encapsulate this hack in a utility method or something:
double number = 54123756.523d;
int prefix = (int)number / 1000;
NumberFormat nf1 = new DecimalFormat("#,##");
String newPrefix = nf1.format(prefix);
double remainder = number - (prefix * 1000);
NumberFormat nf2 = new DecimalFormat("#,###.##");
String newRemainder = nf2.format(remainder);
String finalNum = newPrefix + "," + newRemainder;
System.out.println("Formatted number is " + finalNum);
So see if you can live with the code sample suggested above. It is not ideal or efficient but will at least serve your purpose and won't need any third party libraries.

DecimalFormat , input 123.45 , expect 0123.4500

input :123.45.
expect output : 0123.4500
In my netbean 8.02 jdk 8 the result when I run the following code is: 0123,4500
In other compile online site (tutorialspoint/ ideone) the result is : 0123.4500
I don't understand why my result have the comma instead of dot?
Anyhelp can give me expect output is 0123.4500 ??
public class MainClass{
public static void main(String[] args) {
String out="";
String Format="0000.0000";
DecimalFormat dfm=new DecimalFormat(Format);
out=dfm.format(123.45);
System.out.println("out="+out);
}
}
The comma comes from the Locale on your system. Try setting the default Locale like this
Locale.setDefault(Locale.ENGLISH);
or setting the Locale specificly for this DecimalFormat. Here is one way to do that
NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.ENGLISH);
DecimalFormat dfm = (DecimalFormat) numberFormat;
I don't understand why my result have the comma instead of dot?
That might be because of your locale setting. There are countries which use comma as a separator for decimals.
Try to set your locale as:
Locale.setDefault(Locale.ENGLISH);
IDEONE DEMO

formating a number/string with decimal separator

I am trying to format a Number with DecimalFormat. But I want it to format a number, that is like
input: 1234. --> should be formatted to: 1,234.
But I get 1,234.0 or 1,234.00 depending on my rules for the decimal format
What do I have to do in order to get this done?
The methods that should help you are setMinimumFractionDigits and setMaximumFractionDigits.
format.setMinimumFractionDigits(0);
at a guess, is probably what your looking for.
To ensure that the decimal separator is always shown, use: DecimalFormat.setDecimalSeparatorAlwaysShown(true)
You could format the number regardless of whether it is a decimal or not by using
DecimalFormat f = new DecimalFormat("#,###");
f.format(whatever)...
If you don't want to display any decimal places, don't format a floating point value :) If you use BigInteger, int, or long, it should be fine:
import java.math.*;
import java.text.*;
public class Test {
private static final char p = 'p';
public static void main(String[] args) {
NumberFormat format = new DecimalFormat();
BigInteger value = BigInteger.valueOf(1234);
System.out.println(format.format(value));
System.out.println(format.format(1234));
System.out.println(format.format(1234L));
}
}
Try this:
DecimalFormat df = new DecimalFormat("#,###.", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
System.out.println(df.format(1234));

Categories