Instantiating NumberFormat Class

  • Thread starter friendbobbiny
  • Start date
  • Tags
    Class
In summary, the conversation discusses the issue of not being able to instantiate the type NumberFormat in a method and provides a solution by using a factory class method. The error of trying to use an abstract class directly and a sample of how to use the NumberFormat class are also mentioned.
  • #1
friendbobbiny
49
2
I've imported java.util, java.text and placed the following method under an appropriate class.

I'm unable to pinpoint why compiler can't instantiate the type NumberFormat in my method's second line





public static void tailorFormat(String name, double value, Locale loc){

NumberFormat kitty = new NumberFormat (loc); // <<<<< this is where I've referred to

DecimalFormat shelter = (DecimalFormat) kitty;
shelter.applyPattern(name);
shelter.format(value);
System.out.println(name + " " + value + " " + loc.toString());
}
 
Technology news on Phys.org
  • #2
What is the error that the compiler is telling you?
Usually (but not always) the compiler is actually quite helpful in telling you what you've done wrong :)
 
  • #3
java.text.NumberFormat is an abstract class, so you can't use it directly as you are trying to. Here's a sample of how this class can be used (see http://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html):
To format a number for the current Locale, use one of the factory class methods:
Code:
  myString = NumberFormat.getInstance().format(myNumber);
The web page I linked to has several other examples that might be of help to you.
 
Last edited by a moderator:

FAQ: Instantiating NumberFormat Class

1. What is the purpose of instantiating NumberFormat Class?

Instantiating NumberFormat Class allows you to format numbers according to a specific locale and customize the display of decimal places, currency symbol, and other formatting options.

2. How do I instantiate NumberFormat Class?

You can instantiate NumberFormat Class using the new keyword and passing in the desired locale as a parameter. For example, NumberFormat nf = new NumberFormat(Locale.US);

3. Can I use NumberFormat Class for both formatting and parsing numbers?

Yes, NumberFormat Class can both format and parse numbers. You can use the format() method to convert a number into a formatted string, and the parse() method to convert a string back into a number.

4. How do I customize the formatting options with NumberFormat Class?

You can customize the formatting options by using the setMinimumFractionDigits(), setMaximumFractionDigits(), and setCurrency() methods. These methods allow you to specify the minimum and maximum number of decimal places, as well as the currency symbol to be used in formatting.

5. Is NumberFormat Class thread-safe?

Yes, NumberFormat Class is thread-safe, meaning it can be safely used by multiple threads at the same time without causing conflicts or errors.

Back
Top