Formatting Java String - java

I have a simple question, but it's rather difficult to google. I have an input field for a number, and I need to make this number into a currency. So, if a user inputs 120, I need to format that into $1.20. Then, if they add another digit, say the number becomes 1204, I need to format this as $12.04. I'm using a Double.ParseDouble, but for say 120, this yields $120.00. So, I guess I need something like ParseDouble that will turn a value like 120 into $1.20 instead of $120.00. How do I do this?

use Double.parseDouble(double number);, but easily multiply with 0.01 :)
Then you have your currency and everything is fine ;)
Devlen

You can do it without even parsing in a numeric.
Use a StringBuilder object to do so:
String input = "120";
String output = new StringBuilder(input).insert(input.length() - 2,".")
.insert(0, "$").toString();
System.out.println(output); // Prints $1.20

public String getNumberCurrency(double number){
NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.getDefault());
String moneyString = formatter.format(number/100);
return moneyString;
}

Related

Trimming text in java

is java have method to trimming text/string? like this one :
int comaNumber = input.nextInt();
string number = "234,56789";
int coma = number.indexOf(",");
string number = number.substring(0,coma(comaNumber+1));
note : it will search coma character and then it will trim the number based on amount of coma in comaNumber, the result is 234,56 (works)
is any method in java to trimming decimal number to simplify my works? (not trim() function)
Edit: the number of decimal place is specified by user input.
The easiest way is to use DecimalFormat. Although, to get that working with a comma you will need to modify the FormatSymbols.
It would be something like this:
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');//this tels DecimalFormat to use ',' as the decimal separator
String pattern = "#.00";//this means that you want only 2 decimals
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
System.out.println(decimalFormat.parse("221012,28").doubleValue());
System.out.println(decimalFormat.format(1234.123121));
That prints
221012.28
1234,12
You could try using String.format. First switch the comma with a period. For example,
number = number.replace(",",".");
double y = Double.parseDouble(number);
String x = String.format("%.2d",number);
x = x.replace(".",",");
First, you replace the comma with a period. Then you use the parseDouble method(documentation https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)). Then you use String.format to save it with only two places after the decimal point. Then change decimal back to comma.
Hope this helps!
As far as I know, there is no such method. My advice is to create your own method, and then reference it whenever you need it.

Convert String to Number with Format

I was wondering if there is an existing method to convert a formatted number String to number, such as "123,456.78" to 123456.78
Basically, unlike DecimalFormat function, which turns a double variable to a String following that a given format such as "###,###.##" pattern. I want to implement a reverse of this functionality, which turns a String with "###,###.##" format to a double. Is there APIs to do this?
Thank you.
You should have looked through the documentation for DecimalFormat and its superclass. You would have discovered that it has not only format methods, but also parse methods like this one.
The easiest way to do what you want is:
NumberFormat format = NumberFormat.getInstance();
Number value = format.parse(string);
// If you specifically want a double...
double d = value.doubleValue();
You will have to catch ParseException and deal with it. How you do that depends on what you want to do when your string does not represent a valid numeric value. If it's user input, you may want to ask the user to enter the text again.
Here is a simple way to do this
String number = "20,000,000";
int x = Integer.parseInt(number.replace(",", ""));
System.out.println(x);
You just replace the char's that not belong to a number with "" and then parse it into a primitive.
String number = "20,000,000.56";
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(5);
double x = Double.parseDouble(number.replace(",", ""));
System.out.println(df.format(x));
It is a bit different for a Double cause it will display the exponential output and you'll have to prevent that. The code above does that.
df.format(x)
Returns a String but you can cast it with the Double.parseDouble method
Here's a method using a Regex and the replace method if you have more than one delimiter and you know them all :
Let's say the delimiters here are "-" and ","
double x = Double.parseDouble(number.replace("[-,]", "");

Convert to int from String of numbers having comma

I have value like this:
String x = "10,000";
I want to convert this to int.
I can convert it by removing comma like below:
String y = x.replace(",", "");
int value1 = Integer.parseInt(y);
But I don't want to do it like above.
Any other suggestions like inbuilt function? Or any other recommended ways for this?
You can simply:
NumberFormat.getNumberInstance(Locale.UK).parse(x);
Read about:
NumberFormat
Locale.UK and others.
Try this:
NumberFormat format = NumberFormat.getInstance(Locale.US);
Number number = format.parse("10,000");
// Now you can get number values from the object (like int, long, double)
System.out.println(number.intValue());
Output:
10000
Note: If you string contains values after decimal point, you need to use number.doubleValue to retain the precision because number.intValue() will simply ignore values after decimal points.
Use any one of these:
NumberFormat.getNumberInstance(Locale.ENGLISH).parse("10,000").intValue();
NumberFormat.getNumberInstance(Locale.US).parse("10,000").intValue();
NumberFormat.getNumberInstance(Locale.UK).parse("10,000").intValue();

How to delete spaces in a JFormattedTextField?

here is an exemple of code :
private JFormattedTextField jftf2 = new JFormattedTextField();
try{
MaskFormatter mask = new MaskFormatter("###-####");
mask.install(jftf2);
}catch(ParseException e){e.printStackTrace();}
when I execute it, it shows 3 spaces then '-' then 4 spaces,i want to know how not to have those spaces, a simple empty textfield that receives no more than the characters i write. i know that there is a method mask.setPlaceholderCharacter(' '); that changes the space to another character but I just want to delete it, not to change it.
another problem is while changing the text, for exemple let's take the same mask ###-#### the string 111-1234 is valid in that mask but when i delete the 3 for exemple it shows 111-12 4 instead of 111-124 , it adds a space, how to resolve that ?
thanx
It’s not quite clear what you want as it is a bit strange to use a MaskFormatter and complain that it behaves like a MaskFormatter. But maybe you wish to do something like this:
JFormattedTextField jftf2 = new JFormattedTextField();
final InternationalFormatter fmt=new InternationalFormatter(
new MessageFormat("{0,number,000}-{1,number,0000}"));
jftf2.setFormatterFactory(new JFormattedTextField.AbstractFormatterFactory() {
public JFormattedTextField.AbstractFormatter
getFormatter(JFormattedTextField tf) {
return fmt;
}
});
jftf2.setValue(new Object[]{111,1234});
With this format the value property of the JFormattedTextField will be expressed as an object array of length 2 containing two numbers. The 000 and 0000 in the format specifier above tell it to format the numbers with leading zeros by default (though the user does not need to input them to make a valid input). But you can change it to 0 for compact numbers.

Parsing a String with an Exponent (Java)

I have a string similar to: 7.6E+7.
My question is simple: How do I turn this into its corresponding number: 76000000?
I have tried using substring to isolate the E+7 part, then parse the 7 part, then move the decimal places over 7. Is there an easier way to do this?
Thank you!
long n = Double.valueOf("7.6E+7").longValue();
System.out.println(d);
// prints 76000000 to the output.
I suggest using Double.parseDouble():
double val = Double.parseDouble(str);
where str is the input string.
You can use Double.parseDouble() to get it as a number.
String e = "7.6E+7";
System.out.println(Double.parseDouble(e));
Giving the output 7.6E7. If you do not want the E in the output you can use
NumberFormat f = NumberFormat.getInstance();
f.setGroupingUsed(false);
System.out.println(f.format(Double.parseDouble(e)));
Which will give you the output 76000000 without casting to a whole number. Eg adding 0.1 to the number will give the output 76000000.1
If you are sure the number can ultimately be cast into an integer without losing precision than alternatively you could do:
int d = (int) Double.parseDouble("7.6E+7");
System.out.println(d);
Which prints 76000000 to the output.

Categories

Resources