my code:
private double retailPrice = 699;
DecimalFormat df = new DecimalFormat("#,###.00");
public double getRetailPrice()
{
return df.format(retailPrice);
}
I am trying to format this for a HW assignment. It's not really required, but I wanted to try this as a learning experience. The method should return a double, but when I try to use decimal formatter, it gives an error:
string cannot be converted into a double
but it's not a string...right?
Basically this ends up as part of a StringBuilder object that is written to a csv file, so it needs to be formatted before it is appended to the StringBuilder.
Do this
public String getRetailPrice()
{
return df.format(retailPrice);
}
You are mixing up two things.
A double number is just that: a number. It does not know about formatting. Formatting is when you turn numbers into strings.
Those are two different things, and there is simply no point in wanting to format a double value whilst keeping it a double. Your code is pointless, plain and simple.
Solution: either have the getter return the double value as it is. Or change its return type to string. And maybe rename it to "getPriceAsFormattedString" for example.
format method return type is String, so you have to parse again formatted value into double. like below
public double getRetailPrice() {
return Double.valueOf(df.format(retailPrice));
}
Related
I want to convert some numbers which I got as strings into Doubles, but these numbers are not in US standard locale, but in a different one. How can I do that?
Try java.text.NumberFormat. From the Javadocs:
To format a number for a different Locale, specify it in the call to getInstance.
NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
You can also use a NumberFormat to parse numbers:
myNumber = nf.parse(myString);
parse() returns a Number; so to get a double, you must call myNumber.doubleValue():
double myNumber = nf.parse(myString).doubleValue();
Note that parse() will never return null, so this cannot cause a NullPointerException. Instead, parse throws a checked ParseException if it fails.
Edit: I originally said that there was another way to convert to double: cast the result to Double and use unboxing. I thought that since a general-purpose instance of NumberFormat was being used (per the Javadocs for getInstance), it would always return a Double. But DJClayworth points out that the Javadocs for parse(String, ParsePosition) (which is called by parse(String)) say that a Long is returned if possible. Therefore, casting the result to Double is unsafe and should not be tried!
Thanks, DJClayworth!
NumberFormat is the way to go, but you should be aware of its peculiarities which crop up when your data is less than 100% correct.
I found the following usefull:
http://www.ibm.com/developerworks/java/library/j-numberformat/index.html
If your input can be trusted then you don't have to worry about it.
Just learning java and programming. Had similar question. Found something like this in my textbook:
Scanner sc = new Scanner(string);
double number = sc.nextDouble();
The book says that a scanner automatically decodes what's in a String variabel and that the Scanner class automatically adapts to the language of the set Locale, system Locale being the default, but that's easy to set to something else.
I solved my problem this way. Maybe this could work for the above issue instead of parsing?
Addition: The reason I liked this method was the fact that when using swing dialouge boxes for input and then trying to convert the string to double with parse I got a NumberFormatException. It turned out that parse exclusively uses US-number formatting while Scanner can handle all formats. Scanner made the input work flawlessly even with the comma (,) decimal separator. Since the most voted up answer uses parse I really don't see how it would solve this particular problem. You would have to input your numbers in US format and then convert them to your locale format. That's rather inconvenient when ones numeric keybord is fitted with a comma.
Now you're all free to shred me to pieces ;)
You use a NumberFormat. Here is one example, which I think looks correct.
Use NumberFormat.getNumberInstance(Locale)
This should be no problem using java.text.DecimalFormat.
Do you know which locale it is? Then you can use
DecimalFormat format = DecimalFormat.getInstance(theLocale);
format.parse(yourString);
this will even work for scientific notations, strings with percentage signs or strings with currency symbols.
Here is how you use parseDouble to convert a String to a Double:
doubleExample.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class doubleExample {
public static void main(String[] args) {
Double myDouble = new Double("0");
System.out.println("Please enter a number:");
try
{
//get the number from console
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
myDouble = Double.parseDouble(br.readLine());
}
//if invalid value was entered
catch(NumberFormatException ne)
{
System.out.println("Invalid value" + ne);
System.exit(0);
}
catch(IOException ioe)
{
System.out.println("IO Error :" + ioe);
System.exit(0);
}
System.out.println("Double value is " + myDouble);
}
}
In Java, the class java.util.Scanner provides a convenient way to parse long strings. In my particular case I have to parse a string with many double values, for which I use the nextDouble() method.
Sometimes, my input string contains nan instead of a valid float number. Unfortunately, Scanner only seems to recognize NaN for not-a-number.
Is there any way to teach it to also recognize nan? Maybe by setting a custom Locale with DecimalFormatSymbols.setNaN()?
How about something like this?
private static final Pattern nan =
Pattern.compile("nan", Pattern.CASE_INSENSITIVE);
public static boolean hasNextDouble(Scanner scanner) {
if(scanner == null)
return false;
return scanner.hasNext(nan) || scanner.hasNextDouble();
}
public static double nextDouble(Scanner scanner) {
if(scanner.hasNext(nan)) {
scanner.next();
return Double.NaN;
}
return scanner.nextDouble();
}
One option is setting a custom Locale. Another option is that internally the scanner uses a regular expression to retrieve a double-string and then uses Double.parseDouble to convert it to a double, so you could call Scanner#next(Pattern pattern) using the regular expression defined here except using "nan" instead of "NaN" and then call Double.parseDouble on the returned string.
I'm trying to set an int value using jTextField and the setText method. But of course setText wants a String. How do I get round this? I'll give you a snippet of the code:
private void setAllTextFields(FilmSystem e){
getFilmNameTF().setText(e.getFilmName());
lectureTF.setText(e.getLecture());
ageTF.setText(e.getAge());
priceTF.setText(e.getTicketCost());
seatsTF.setText(e.getNoOfSeats());
seatsTF is a jTextField and getNoOfSeats is a method in another class that returns a int value.
Thanks again for answering this question. Now how would I go about getting the value of the int to do something to do?
public void buyTicket() {
String newFilmName = filmNameTF.getText();
String newLecture = lectureTF.getText();
String newAge = ageTF.getText();
String newPrice = priceTF.getText();
int newSeats = seatsTF.
As you can see the code, the String values I can get easy with getText. I can then print them out or whatever with them. How can I do this with the seats int? Thanks again.
String#valueOf convert your int to String.
String.valueOf(e.getAge()); will return the string representation of the int argument.
seatsTF.setText(String.valueOf(e.Age()));
...
USe
seatsTF.setText(""+e.getNoOfSeats());
OR
seatsTF.setText(String.valueOf(e.getNoOfSeats()));
Normal ways would be
seatsTF.setText(Integer.toString(e.getNoOfSeats()));
or
seatsTF.setText(String.valueOf(e.getNoOfSeats()));
but, this can be achieved with a concatenation like this:
seatsTF.setText("" + e.getNoOfSeats());
Assuming age field is of type int, you could try something like:
ageTF.setText( Integer.toString(e.getAge()) );
Setting an int converting it to a String not a big deal. Displaying a value is a problem. To take care of how the value is displayed properly in the textfield you may use a DecimalFormat to format the numeric value. But may be the number is locale specific then you need NumberFormat instance
NumberFormat nf = NumberFormat.getInstance(locale);
nf.setMaximumIntegerDigits(12);
nf.setMaximumFractionDigits(0);
nf.setMinimumFractionDigits(0);
String s = nf.format(e.getNoOfSeats());
seatsTF.setText(s);
You may also need to read the tutorial on how to use the DecimalFormat.
To convert Integer Value to String you should
MedicineTM medicine=tblmedicine.getSelectionModel().getSelectedItem();
txtmedicine.setText(medicine.getMID());
txtDescription.setText(medicine.getDescription());
txtQty.setText(String.valueOf(medicine.getQty())); // this is what i did
cmbApproval.setValue(medicine.getApproval());
I think you should write the code as
seatsTF.setText(e.getNoOfSeats().toString());
I am currently working on an Android project where we use string numbers with many digits in it.
So I want to know whether there is a way to convert the string numbers for e.g 1000000000 into comma separated string numbers for e.g(1,00,00,00,000) in Indian Locale format.
I got the US locale format string conversion but I want Indian locale format.
I would use format("% ,d", number) method of Format class, ensuring that I initialize the Formatter object with the appropriate locale (which I believe is en_IN for Indian).
Having said that, it would be easier for people to help you if you posted code on how you are doing it for US locale in the first place.
Ref : Formatting a Number Using a Custom Format
private String getFormatedData(String unformatedData) {
if(unformatedData != null) {
try {
//unformatedData.replaceAll(",", "");
Double result = Double.valueOf(unformatedData);
DecimalFormat myFormatter = new DecimalFormat("###,##0.00");
//DecimalFormat myFormatter = new DecimalFormat("#,###,###");
//If you don't want to show .00 format
return myFormatter.format(result);
} catch (NumberFormatException e) {
return unformatedData;
}
} else {
return "0.00";
}
}
Use this method.
I think you have to modify this method if you don't need .00 value. Let me work on it.
I think that you need to use NumberFormat so you can make a general case using current Locale settings of the user.
And I think that this is your current situation:
If you are formatting multiple numbers, it's more efficient to get the format and use it multiple times so that the system doesn't have to fetch the information about the local language and country conventions multiple times.
NumberFormat nf = NumberFormat.getInstance();
for (int i = 0; i < a.length; ++i) {
output.println(nf.format(myNumber[i]) + "; ");
}
The answer given by Pankaj Kumar gives the output in US format not in Indian Format.
If you want in US format it can be easily done by following code:
NumberFormat.getNumberInstance(Locale.US).format(35634646)
As shown here: Converting Integer to String with comma for thousands
To get the string with commas in Indian Format you can try this manual code
public String round(String d)
{
ArrayList<Integer> commas=new ArrayList<Integer>();
String output=null;
char[] preDecimal=d.split("[.]")[0].toCharArray();
int i=preDecimal.length-3;
System.out.println(i);
while(i>0)
{
commas.add(i);
i-=2;
}
StringBuilder sb=new StringBuilder();
for(i=0;i<preDecimal.length;i++)
{
sb.append(preDecimal[i]);
if(commas.contains(i+1))
sb.append(",");
}
output=sb.toString();
return output;
}
I using:
String str="300.0";
System.out.println(Integer.parseInt(str));
return an exception:
Exception in thread "main" java.lang.NumberFormatException: For input string: "300.0"
How can I parse this String to int?
thanks for help :)
Here's how you do it:
String str = "300.0";
System.out.println((int) Double.parseDouble(str));
The reason you got a NumberFormatException is simply that the string ("300.00", which is a floating point number) could not be parsed as an integer.
It may be worth mentioning, that this solution prints 300 even for input "300.99". To get a proper rounding, you could do
System.out.println(Math.round(Double.parseDouble("300.99"))); // prints 301
I am amazed no one has mentioned BigDecimal.
It's really the best way to convert string of decimal's to int.
Josuha Bloch suggest using this method in one of his puzzlers.
Here is the example run on Ideone.com
class Test {
public static void main(String args[]) {
try {
java.math.BigDecimal v1 = new java.math.BigDecimal("30.0");
java.math.BigDecimal v2 = new java.math.BigDecimal("30.00");
System.out.println("V1: " + v1.intValue() + " V2: " + v2.intValue());
} catch(NumberFormatException npe) {
System.err.println("Wrong format on number");
}
}
}
You should parse it to double first and then cast it to int:
String str="300.0";
System.out.println((int)(Double.parseDouble(str)));
You need to catch NumberFormatExceptions though.
Edit: thanks to Joachim Sauer for the correction.
You can use the Double.parseDouble() method to first cast it to double and afterwards cast the double to int by putting (int) in front of it. You then get the following code:
String str="300.0";
System.out.println((int)Double.parseDouble(str));
Integer.parseInt() has to take a string that's an integer (i.e. no decimal points, even if the number is equivalent to an integer. The exception you're getting there is essentially saying "you've told me this number is an integer, but this string isn't in a valid format for an integer!"
If the number contains a decimal component, then you'll need to use Double.parseDouble(), which will return a double primitive. However, since you're not interested in the decimal component you can safely drop it by just casting the double to an int:
int num = (int)Double.parseDouble(str);
Note however that this will just drop the decimal component, it won't round the number up at all. So casting 1.2, 1.8 or 1.999999 to an int would all give you 1. If you want to round the number that comes back then use Math.round() instead of just casting to an int.