How to remove comma from TextField in Java - java

I have a JFormattedTextField with the Name Hectare. The double type value is declared as shown below
String cultivationSize = JFormattedTextField3.getText();
double hectare = Double.parseDouble(cultivationSize);
Now the problem is that when i enter more than 3 digits, by default the comma is entered after 3 digits, e.g. 1,000. I have to add this value to some other value. But, due to this comma,I am unable to do it.
How can I remove comma and add this value to some other value?

Call the getValue() instead of getText() on JFormattedTextField

A much easier solution
Format format = NumberFormat.getIntegerInstance();
format.setGroupingUsed(false);
JFormattedTextField jtf = new JFormattedTextField(format);
This will remove the grouping of the numbers using comma.

You should use MaskFormater like this:
zipField = new JFormattedTextField(
createFormatter("#####"));
...
protected MaskFormatter createFormatter(String s) {
MaskFormatter formatter = null;
try {
formatter = new MaskFormatter(s);
} catch (java.text.ParseException exc) {
System.err.println("formatter is bad: " + exc.getMessage());
System.exit(-1);
}
return formatter;
}

use string.replace(",","");
i.e. your code should look like -
double hectare = Double.parseDouble(cultivationSize.replaceAll(",",""));

Related

How to format currency with number format classes

I am new in Android development and i am stuck at a place. I want to format my currency, I am setting to show without decimal places and with commas.
Example: right now it's showing like 23000.00. But I want the currency like 23,000; how can I do that?
I tried the formatter classes but that doesn't help me.
This is how it's set now.
public class CurrencyFormatter {
public static String setsymbol(BigDecimal data, String currency_symbol)
{
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.ENGLISH);
format.setCurrency(Currency.getInstance(currency_symbol));
String result=data+" "+" دينار";
return result;
}
}
I expect output to be (arabic text)23,000 instead of (arabic test)23000.00
Basically, you need a currency formatter object.
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
After that you can format an amount of money:
Double currencyAmount = new Double(23000.00);
String formattedOutput = currencyFormatter.format(currencyAmount);
There are more options and explanations available here on Oracle's reference document: https://docs.oracle.com/javase/tutorial/i18n/format/numberFormat.html
check this
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.getDefault());
format.setCurrency(Currency.getInstance("USA"));
String result = format.format(1234567.89);
This is the format set of usa you can change with your country code
reference check description here
Try this, it will show in this format 23,000 without decimal points, It will show thousand separator in the number.
String result = null;
try {
// The comma in the format specifier does the trick
result = String.format("%,d", Long.parseLong(data)); // use this result variable where you want to use.
result = result + " " + " دينار"; // to append arabic text, do as you were doing before.
} catch (NumberFormatException e) {
}

How to parse String, with both decimal separators comma and dot as well, to Double

I need to input number as a String from user and parse it to the Double object.
I'd like it to be available to take comma, as a decimal separator, and dot as well and save it and outuput only with a dot.
Example: 22,33-->22.33 and 22.33-->22.33
What I use is:
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
try {
Number number = format.parse(formDto.getWeight());
kitten.setWeight(number.doubleValue());
} catch (ParseException e) {
e.printStackTrace();
}
But it only gets values with ',' separator. When user inputs with dot it loses all decimals and returns that 22.33 -->22.0 or 4.1 --> 4.0
When i debug i see that it's a parsing problem (obvious) but have no idea what is good practice to solve it.
You can replace the dot "." with comma :," before the parsing.
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
try {
Number number = format.parse(formDto.replace('.', ',').getWeight());
kitten.setWeight(number.doubleValue());
} catch (ParseException e) {
e.printStackTrace();
}
Like Mohit Thakur said, but compilable.
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
try {
Number number = format.parse(formDto.getWeight().replace('.', ','));
kitten.setWeight(number.doubleValue());
} catch (ParseException e) {
e.printStackTrace();
}
Once try with this:
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
try {
Number number = Double.parseDouble(format.replace(",", ".").getWeight());
kitten.setWeight(number.doubleValue());
} catch (ParseException e) {
e.printStackTrace();
}
Thanks.
If you just want to convert your String to Double value then it can be done with the below approach
String numberStr1 = "22,33"; //number with comma as decimal separator
String numberStr2 = "22.33"; //number with dot as decimal separator
System.out.println(numberStr1.contains(",") ? Double.valueOf(numberStr1.replace(',', '.')):Double.valueOf(numberStr1));
System.out.println(numberStr2.contains(",") ? Double.valueOf(numberStr2.replace(',', '.')):Double.valueOf(numberStr2));
I have used Java Tertiary Operator to achieve this task. You can store the double value instead of printing to screen.
If this does not help or you want to do it specifically with NumberFormat then do let me know in comments.

How to format a math expression inside a text field?

I'm creating a Calculator software. In the text field as I'm typing, the whole expression appears as one string (and I want to keep it this way). Here's a demo:
I want it to be formatted like this:
NUMBERS - ###.###.###,###### (Grouping them into 3 digit groups, displaying fractions ONLY when needed and only up to 6 digits.)
Operators and Parenthesis - ###×(###-###)/### (Should not cause any formatting errors or problems. I don't care if there is or there isn't a space inbetween the numbers and operators/parenthesis.)
Here's the above example in the correct format:
1.000×(5-3)/2
I also want it to automatically update the formatting as I'm typing.
Sofar I tried using JFormattedTextField with MaskFormatters and NumberFormat but neither of them worked as (described above) I wanted to.
NumberFormat version.
public class Frame {
private NumberFormat numberFormat = NumberFormat.getInstance();
private JFormattedTextField textField = new JFormattedTextField(numberFormat);
}
MaskFormatter version.
public class Frame {
private MaskFormatter maskFormat;
private JFormattedTextField textField;
public Frame() {
try {
maskFormat = new MaskFormatter("###.###.###,######");
} catch (ParseException e) {
e.printStackTrace();
}
textField = new JFormattedTextField(maskFormat);
}
}
I managed to format the result using DecimalFormat but I don't want only the result to be formatted.
Formatting the result.
DecimalFormat resultFormat = new DecimalFormat("###,###,###.######");
String result = resultFormat.format(Parser.evaluate(expression));
textField.setText(result);
When I calculate 5/3 the result is:
Just as I wanted.
Sorry for such a detailed and long post, any help is greatly appreciated!
Try this.
DecimalFormat resultFormat = new DecimalFormat("###,###,###.######");
Pattern numberPattern = Pattern.compile("\\d+(\\.\\d+)?");
String s = "1000×(5-3)/2";
Matcher m = numberPattern.matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find()) {
double value = Double.parseDouble(m.group());
String formatted = resultFormat.format(value);
m.appendReplacement(sb, formatted);
}
m.appendTail(sb);
System.out.println(sb);
// -> 1,000×(5-3)/2

How to format this string in java?

How can a String be formatted in Java?
My String contains only numbers like "1234.0" and I want to return the formatted number.
For example, given the string "1234.0" the result should be the String "1234".
You can use regular expressions as well:
String n = "1234.0";
n.replaceAll("\\.0*$", "");
try {
String formatted = String.valueOf((int)Double.parseDouble("12345.0"));
} catch (ParseException e) {
// input is not a number
}
Use DecimalFormat like this:
DecimalFormat myFormatter = new DecimalFormat("####");
String output = myFormatter.format(value);
You can find more here

How to parse only valid numbers in default locale using NumberFormat

I'm using a NumberFormat instance to parse text using default locale.
If a string is not a valid numeric value, I have to return 0. The problem is that parse method,according to Javadocs:
Parses text from the beginning of the given string to produce a
number. The method may not use the entire text of the given string.
So, if I parse (I'm using italian locale) "BAD 123,44" I correctly get a ParseException and return 0, but if I parse "123,44 BAD", I get a value of 123.44, while I have to return 0 in this case.
And worse, if I parse "123.44 BAD", I get value 12344!
class RateCellReader {
public static final NumberFormat NUMBER_FORMAT =
NumberFormat.getNumberInstance(Locale.getDefault());
...
try {
number = NUMBER_FORMAT.parse(textValue);
} catch (ParseException e) {
number = 0;
}
...
}
How can I do an exact parse of text, or check if text correctly represent a number in default locale?
EDIT:
Getting inspired by the response linked by #yomexzo, I changed my code like this:
class RateCellReader {
public static final NumberFormat NUMBER_FORMAT =
NumberFormat.getNumberInstance(Locale.getDefault());
...
ParsePosition pos = new ParsePosition(0);
number = NUMBER_FORMAT.parse(textValue,pos);
if (textValue.length() != pos.getIndex())
number = 0;
...
}
How about this
boolean isValid;
try {
Number n = NUMBER_FORMAT.parse(s1);
String s2 = NUMBER_FORMAT.format(n);
isValid = s1.equals(s2);
}catch(ParseException e) {
isValid = false;
}

Categories

Resources