- Decoding numbers with comma as decimal separator
- Parsing double with comma as decimal separator
- Parsing double superCSV with comma as decimal separator?
- Parsing a string value to double with comma decimal seperator
- How can I make a JTextField accept double value with comma as the separator?
- Best way to parseDouble with comma as decimal separator?
- Solution 3
- Solution 4
- Solution 5
- Best Way to Parsedouble With Comma as Decimal Separator
- Best way to parseDouble with comma as decimal separator?
- How to parse String, with both decimal separators comma and dot as well, to Double
- Parse strings to double with comma and point
- Is there a standard way to parse a float using a custom decimal separator
- Convert a String to Double — Java
- DecimalFormat(0.0) returns data with a comma as separator instead of a point
- Лучший способ parseDouble с запятой в качестве десятичного разделителя?
Decoding numbers with comma as decimal separator
Solution 3: When submitting, iterate through the text field and replace any occurrence of a comma with a decimal. The method has a functionality that returns the last valid edit, which in your case would be a decimal. Familiarize yourself with the libraries. Solution 2: Upon pressing the button, replace the comma with a dot. Afterward, utilize the text variable instead of the textfield.getText().
Parsing double with comma as decimal separator
With NumberFormat , it is possible to perform actions such as this:
NumberFormat f = NumberFormat.getInstance(Locale.FRANCE); double myNumber = f.parse("3,5").doubleValue();
Now, you can provide the method that accepts a double value with myNumber as an argument.
In Java, when utilizing Locale.FRANCE , you specify that you express numbers using , instead of . .
Here is an example of how to utilize DecimalFormat .
DecimanFormat df = new DecimalFormat("#.#", DecimalFormatSymbols.getInstance()); Double returnValue = Double.valueOf(df.format(input1));
The default locale and its corresponding symbols will be obtained by DecimalFormatSymbols.getInstance() .
For additional information on DecimalFormat , please click here. «»».
I believe that the input you provided through the scanner is.
The strings have been divided into substrings, specifically 3.5 and 5.3, when you provide your input.
The compilation will be error-free and successful.
in your case
To achieve this, simply add a comma within the split method, for example:
It will function with the resulting output as .
Best way to parseDouble with comma as decimal, Because of the comma used as the decimal separator, this code throws a NumberFormatException: String p="1,234"; Double d=Double.valueOf(p); System.out.println(d); Is there a better way to Code sampleNumberFormat format = NumberFormat.getInstance(Locale.FRANCE);Number number = format.parse(«1,234»);double d = number.doubleValue();Feedback
Parsing double superCSV with comma as decimal separator?
The use of a French-style decimal separator (comma) is not supported in ParseDouble , but it is supported in ParseBigDecimal . If you find this feature useful, consider submitting a feature request.
To avoid repetition, a straightforward solution is to use the StrReplace function before the ParseDouble in order to replace the comma with a full stop.
new StrReplace(",", ".", new ParseDouble())
Instead, you have the option to create a specialized cell processor that can either:
- parses a Double (with a configurable decimal separator)
- converts a BigDecimal to a Double (calling doubleValue() ) — this can then be chained after your new ParseBigDecimal(FRENCH_SYMBOLS)
In the future, it would be helpful if you specify that your file is separated by semi-colons and inform that you have configured Super CSV with CsvPreference.EXCEL_NORTH_EUROPE_PREFERENCE 🙂
Parsing double with comma as decimal separator, Using NumberFormat you can do something like this: NumberFormat f = NumberFormat.getInstance (Locale.FRANCE); double myNumber = f.parse («3,5»).doubleValue (); Now you can pass myNumber to the method that accepts double value. When using Locale.FRANCE, you tell Java …
Parsing a string value to double with comma decimal seperator
Simply indicate the relevant culture for double.Parse . As an illustration:
CultureInfo french = new CultureInfo("fr-FR"); double x = double.Parse("7,50", french);
I have a suspicion that you originally had the value «7,5», but if you were using a culture that does not use a comma as a separator, it would be parsed as «750».
When dealing with currency values, it is advisable to use decimal initially, rather than double «»».
Parsing double superCSV with comma as decimal, The simplest workaround is to simply chain a StrReplace before the ParseDouble to convert the comma to full stop. new StrReplace («,», «.», new ParseDouble ()) Alternatively, you could write a custom cell processor that either: parses a Double (with a configurable decimal separator)
How can I make a JTextField accept double value with comma as the separator?
If you possess a NumberFormat , you have everything necessary. Simply substitute Double.parse with NumberFormat.parse . However, it becomes even more convenient when employing a JFormattedTextField (infer its purpose from the class name). Provide the desired NumberFormat to the constructor, for example, new JFormattedTextField(nf) . The JFormattedTextField features a method called getValue that retrieves the most recent valid edit. In the case of your NumberFormat , it will be a Number .
Upon pressing the button, it is possible to substitute the comma with a dot.
Subsequently, the text variable should be utilized instead of textfield.getText().
When submitting, iterate through the text field and replace any commas with decimals. After the loop, convert the string to a double.
Parsing a string value to double with comma decimal, 1 Answer. Just specify the appropriate culture to double.Parse. For example: CultureInfo french = new CultureInfo («fr-FR»); double x = double.Parse («7,50», french); I suspect you actually had «7,5» as a value, however — as «7,50» would be parsed as «750» if you were using a culture which didn’t use comma as the …
Best way to parseDouble with comma as decimal separator?
Or you can use java.text.DecimalFormat and set the appropriate symbols:
DecimalFormat df = new DecimalFormat(); DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator(','); symbols.setGroupingSeparator(' '); df.setDecimalFormatSymbols(symbols); df.parse(p);
Solution 3
As E-Riz points out, NumberFormat.parse(String) parse «1,23abc» as 1.23. To take the entire input we can use:
public double parseDecimal(String input) throws ParseException < NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.getDefault()); ParsePosition parsePosition = new ParsePosition(0); Number number = numberFormat.parse(input, parsePosition); if(parsePosition.getIndex() != input.length())< throw new ParseException("Invalid input", parsePosition.getIndex()); >return number.doubleValue(); >
Solution 4
Double.parseDouble(p.replace(',','.'))
. is very quick as it searches the underlying character array on a char-by-char basis. The string replace versions compile a RegEx to evaluate.
Basically replace(char,char) is about 10 times quicker and since you’ll be doing these kind of things in low-level code it makes sense to think about this. The Hot Spot optimiser will not figure it out. Certainly doesn’t on my system.
Solution 5
If you don’t know the correct Locale and the string can have a thousand separator this could be a last resort:
doubleStrIn = doubleStrIn.replaceAll("[^\\d,\\.]++", ""); if (doubleStrIn.matches(".+\\.\\d+,\\d+$")) return Double.parseDouble(doubleStrIn.replaceAll("\\.", "").replaceAll(",", ".")); if (doubleStrIn.matches(".+,\\d+\\.\\d+$")) return Double.parseDouble(doubleStrIn.replaceAll(",", "")); return Double.parseDouble(doubleStrIn.replaceAll(",", "."));
Be aware: this will happily parse strings like «R 1 52.43,2» to «15243.2».
Best Way to Parsedouble With Comma as Decimal Separator
Best way to parseDouble with comma as decimal separator?
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();
To support multi-language apps use:
NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
How to parse String, with both decimal separators comma and dot as well, to Double
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();
>
Parse strings to double with comma and point
You want to treat dot ( . ) like comma ( , ). So, replace
if (double.TryParse(values[i, j], out tmp))
if (double.TryParse(values[i, j].Replace('.', ','), out tmp))
Is there a standard way to parse a float using a custom decimal separator
Alternative 1: Replace «,» with «.» (as already suggested)
Alternative 2: Use DecimalFormat
float value;
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
df.setDecimalFormatSymbols(symbols);
try Number n = df.parse("1,234");
value = n.floatValue();
> catch (ParseException e) e.printStackTrace();
>
Convert a String to Double — Java
Have a look at java.text.NumberFormat . For example:
import java.text.*;
import java.util.*;
public class Test
// Just for the sake of a simple test program!
public static void main(String[] args) throws Exception
NumberFormat format = NumberFormat.getInstance(Locale.US);
Number number = format.parse("835,111.2");
System.out.println(number); // or use number.doubleValue()
>
>
Depending on what kind of quantity you’re using though, you might want to parse to a BigDecimal instead. The easiest way of doing that is probably:
BigDecimal value = new BigDecimal(str.replace(",", ""));
or use a DecimalFormat with setParseBigDecimal(true) :
DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US);
format.setParseBigDecimal(true);
BigDecimal number = (BigDecimal) format.parse("835,111.2");
DecimalFormat(0.0) returns data with a comma as separator instead of a point
You can (and you actually need to avoid localization) actively configure the DecimalFormat with more detail as follows:
public class Main public static void main(String[] args) throws Exception DecimalFormat df = new DecimalFormat("0.0");
DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
decimalFormatSymbols.setDecimalSeparator('.');
df.setDecimalFormatSymbols(decimalFormatSymbols);
System.out.println(df.format(10.4)); // prints 10,4 instead of 10.4
System.out.println(df.format(100.5)); // prints 100,5 instead of 100.5
System.out.println(df.format(3000.3));// prints 3000,3 instead of 3000.3
>
>
You can read more details in the reference documentation, where an important snippet can be read:
Special Pattern Characters
(. )
The characters listed here are used
in non-localized patterns. Localized patterns use the corresponding
characters taken from this formatter’s DecimalFormatSymbols object
instead, and these characters lose their special status.
Лучший способ parseDouble с запятой в качестве десятичного разделителя?
Есть ли лучший способ разобрать «1,234» , чтобы получить 1.234 , чем: p = p.replaceAll(«,»,».»); ?
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE); Number number = format.parse("1,234"); double d = number.doubleValue();
Вы можете использовать это (французский язык имеет , для десятичного разделителя)
NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE); nf.parse(p);
Или вы можете использовать java.text.DecimalFormat и установить соответствующие символы:
DecimalFormat df = new DecimalFormat(); DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator(','); symbols.setGroupingSeparator(' '); df.setDecimalFormatSymbols(symbols); df.parse(p);
Как указывает E-Riz, NumberFormat.parse(String) анализирует “1,23abc” как 1.23. Чтобы взять весь ввод, мы можем использовать:
public double parseDecimal(String input) throws ParseException < NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.getDefault()); ParsePosition parsePosition = new ParsePosition(0); Number number = numberFormat.parse(input, parsePosition); if(parsePosition.getIndex() != input.length())< throw new ParseException("Invalid input", parsePosition.getIndex()); >return number.doubleValue(); >
Если вы не знаете правильный язык и у строки может быть разделитель на тысячу, это может быть последним:
doubleStrIn = doubleStrIn.replaceAll("[^\\d,\\.]++", ""); if (doubleStrIn.matches(".+\\.\\d+,\\d+$")) return Double.parseDouble(doubleStrIn.replaceAll("\\.", "").replaceAll(",", ".")); if (doubleStrIn.matches(".+,\\d+\\.\\d+$")) return Double.parseDouble(doubleStrIn.replaceAll(",", "")); return Double.parseDouble(doubleStrIn.replaceAll(",", "."));
Знайте: это будет радостно анализировать строки типа “R 1 52.43,2” на “15243.2”.
Это статический метод, который я использую в своем собственном коде:
public static double sGetDecimalStringAnyLocaleAsDouble (String value) < if (value == null) < Log.e("CORE", "Null value!"); return 0.0; >Locale theLocale = Locale.getDefault(); NumberFormat numberFormat = DecimalFormat.getInstance(theLocale); Number theNumber; try < theNumber = numberFormat.parse(value); return theNumber.doubleValue(); >catch (ParseException e) < // The string value might be either 99.99 or 99,99, depending on Locale. // We can deal with this safely, by forcing to be a point for the decimal separator, and then using Double.valueOf . //http://stackoverflow.com/questions/4323599/best-way-to-parsedouble-with-comma-as-decimal-separator String valueWithDot = value.replaceAll(",","."); try < return Double.valueOf(valueWithDot); >catch (NumberFormatException e2) < // This happens if we're trying (say) to parse a string that isn't a number, as though it were a number! // If this happens, it should only be due to application logic problems. // In this case, the safest thing to do is return 0, having first fired-off a log warning. Log.w("CORE", "Warning: Value is not a number" + value); return 0.0; >> >
Double.parseDouble(p.replace(',','.'))
… очень быстро, поскольку он ищет базовый массив символов на основе char -by- char. Строка, заменяющая версии, компилирует RegEx для оценки.
В основном заменить (char, char) примерно в 10 раз быстрее, и поскольку вы будете делать такие вещи в низкоуровневом коде, имеет смысл подумать об этом. Оптимизатор Hot Spot не поймет этого… Конечно, в моей системе нет.
Вам, конечно, нужно использовать правильный язык. Этот вопрос поможет.
Double.parseDouble(p.replace(',','.'));