Convert a String to Double - Java - java

What is the easiest and correct way to convert a String number with commas (for example: 835,111.2) to a Double instance.
Thanks.

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");

The easiest is not always the most correct. Here's the easiest:
String s = "835,111.2";
// NumberFormatException possible.
Double d = Double.parseDouble(s.replaceAll(",",""));
I haven't bothered with locales since you specifically stated you wanted commas replaced so I'm assuming you've already established yourself as a locale with comma is the thousands separator and the period is the decimal separator. There are better answers here if you want correct (in terms of internationalization) behavior.

Use java.text.DecimalFormat:
DecimalFormat is a concrete subclass
of NumberFormat that formats decimal
numbers. It has a variety of features
designed to make it possible to parse
and format numbers in any locale,
including support for Western, Arabic,
and Indic digits. It also supports
different kinds of numbers, including
integers (123), fixed-point numbers
(123.4), scientific notation (1.23E4),
percentages (12%), and currency
amounts ($123). All of these can be
localized.

A link can say more than thousand words
// Format for CANADA locale
Locale locale = Locale.CANADA;
String string = NumberFormat.getNumberInstance(locale).format(-1234.56); // -1,234.56
// Format for GERMAN locale
locale = Locale.GERMAN;
string = NumberFormat.getNumberInstance(locale).format(-1234.56); // -1.234,56
// Format for the default locale
string = NumberFormat.getNumberInstance().format(-1234.56);
// Parse a GERMAN number
try {
Number number = NumberFormat.getNumberInstance(locale.GERMAN).parse("-1.234,56");
if (number instanceof Long) {
// Long value
} else {
// Double value
}
} catch (ParseException e) {
}

There is small method to convert german price format
public static BigDecimal getBigDecimalDe(String preis) throws ParseException {
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
Number number = nf.parse(preis);
return new BigDecimal(number.doubleValue());
}
----------------------------------------------------------------------------
German format BigDecimal Preis into decimal format
----------------------------------------------------------------------------
public static String decimalFormat(BigDecimal Preis){
String res = "0.00";
if (Preis != null){
NumberFormat nf = NumberFormat.getInstance(Locale.GERMANY);
if (nf instanceof DecimalFormat) {
((DecimalFormat) nf).applyPattern("###0.00");
}
res = nf.format(Preis);
}
return res;
}
---------------------------------------------------------------------------------------
/**
* This method converts Deutsche number format into Decimal format.
* #param Preis-String parameter.
* #return
*/
public static BigDecimal bigDecimalFormat(String Preis){
//MathContext mi = new MathContext(2);
BigDecimal bd = new BigDecimal(0.00);
if (!Util.isEmpty(Preis)){
try {
// getInstance() obtains local language format
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
nf.setMinimumFractionDigits(2);
nf.setMinimumIntegerDigits(1);
nf.setGroupingUsed(true);
java.lang.Number num = nf.parse(Preis);
double d = num.doubleValue();
bd = new BigDecimal(d);
} catch (ParseException e) {
e.printStackTrace();
}
}else{
bd = new BigDecimal(0.00);
}
//Rounding digits
return bd.setScale(2, RoundingMode.HALF_UP);
}

Related

Format BigDecimal number with commas upto 2 decimal places

I want to format BigDecimal numbers with comma and 2 decimal places.
If the decimal values in BigDecimal number are 0 then I want to remove the trailing zeros also.
E.g
Amount is 20000.00 and should be formatted to 20,000
Amount is 167.50 and should be formatted to 167.50
Amount is 20000.75 and should be formatted to 20,000.75
I have used this method-
public static String getNumberFormattedString(BigDecimal bigDecimal) {
if (bigDecimal != null) {
NumberFormat nf = NumberFormat.getInstance(new Locale("en", "IN"));
nf.setMinimumFractionDigits(0);
nf.setMaximumFractionDigits(2);
nf.setGroupingUsed(true);
return nf.format(bigDecimal);
}
return "";
}
This is not returning correct output for big decimal input 167.50.
The formatted output is coming as 167.5
You can use NumberFormat for what you want. Here is the function I use:
public static String GenerateFormat(Double value) {
if (value == null) return "";
NumberFormat nf = NumberFormat.getInstance(new Locale("de", "DE"));
nf.setMinimumFractionDigits(0);
nf.setMaximumFractionDigits(2);
nf.setGroupingUsed(true);
return nf.format(value);
}
In this, you can see that I am providing Locale as a parameter for NumberFormat. Each country has its own number formatting standard, and what you want can be achieved with this locale new Locale("en", "US"). Inside setMaximumFractionDigits you can place how much of fraction digits you want, in your case it is 2.
EDIT
Because of your situation, try this:
public static String GenerateFormat(Double value) {
if (value == null) return "";
NumberFormat nf = NumberFormat.getInstance(new Locale("de", "DE"));
if (value%1 == 0) nf.setMinimumFractionDigits(0);
else nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
nf.setGroupingUsed(true);
return nf.format(value);
}

BigDecimal format with exponential

I have a problem with formating BigDecimal in Java (Android Studio)!
I want to format BigDecimal to String when it is bigger than 16 characters, with 9 decimals plus exponential (0.000000000e+00).
I used String#format but the result is not correct, it is 1.000000000e+32 instead of 9.99999999e+31.
How can I get the number in the correct format? Here is the code.
String b = "9999999999999999";
String c = "9999999999999999";
BigDecimal resultMultyply = (new BigDecimal(b)).multiply(new BigDecimal(c));
String main_number = resultMultyply.toString();
if (main_number.length() > 16) {
// main_number = 99999999999999980000000000000001
main_number = String.format("%16.9e", new BigDecimal(main_number));
// main_number = 1.000000000e+32
}
main_number is correct before formatting.
Use DecimalFormat with rounding mode DOWN
Your problem is that you don't have your hands on the rounding mode when creating your output value. The default rounding mode for BigDecimal is HALF_UP, which is not what you want: you want to see the first digits as is. So that means you discard the digits after your expected precision, which translates into rounding DOWN. Unfortunately, BigDecimal doesn't offer such fine grain by default. So you have to use DecimalFormat.
All in all, it works like this:
import java.math.*;
import java.text.*;
public class Main {
public static void main(String[] args) {
BigDecimal a = new BigDecimal("9999999999999999");
BigDecimal mul = a.multiply(a);
System.out.println(format(mul, 9));
}
private static String format(BigDecimal x, int scale) {
NumberFormat formatter = new DecimalFormat("0.0E0");
formatter.setRoundingMode(RoundingMode.DOWN);
formatter.setMinimumFractionDigits(scale);
return formatter.format(x);
}
}
Outputs:
9.999999999E31

Java format double value with german locale

I have the double value 1400.0 and now I want to format this value into 1.400,00 in Java.
currently I do:
double doubleValue = 1400.0
String pattern = "0.00";
DecimalFormat format = (DecimalFormat)NumberFormat.getNumberInstance(Locale.GERMAN)
format .applyPattern(pattern);
// will be 1400,00 and not 1.400,00
String formattedValue = format.format(doubleValue);
What am I missing?
Try:
String pattern = "#,##0.00";
This pattern tells a DecimalFormat to add the grouping character to the given number.
Edit: Originally I wrote this with zeros, but this would actually create extra zeros for small numbers. Use the # pattern where you don't want initial zeros.
You can try something like this:
class MyClass {
public static void main(String[] args) {
double doubleValue = 74637.96;
Locale locale = Locale.GERMAN;
String string = NumberFormat.getNumberInstance(locale).format(doubleValue);
System.out.println(string);
}
}
and the output will be:
74.637,96
GermanFormat

Java - Is it possible to figure out the DecimalFormat of a string

I am trying to figure out how to, given a decimal through a String calculate the number of significant digits so that I can do a calculation to the decimal and print the result with the same number of significant digits. Here's an SSCCE:
import java.text.DecimalFormat;
import java.text.ParseException;
public class Test {
public static void main(String[] args) {
try {
DecimalFormat df = new DecimalFormat();
String decimal1 = "54.60"; // Decimal is input as a string with a specific number of significant digits.
double d = df.parse(decimal1).doubleValue();
d = d * -1; // Multiply the decimal by -1 (this is why we parsed it, so we could do a calculatin).
System.out.println(df.format(d)); // I need to print this with the same # of significant digits.
} catch (ParseException e) {
e.printStackTrace();
}
}
}
I know DecimalFormat is to 1) tell the program how you intend your decimal to be displayed (format()) and 2) to tell the program what format to expect a String-represented decimal to be in (parse()). But, is there a way to DEDUCE the DecimalFormat from a parsed string and then use that same DecimalFormat to output a number?
Use BigDecimal:
String decimal1 = "54.60";
BigDecimal bigDecimal = new BigDecimal(decimal1);
BigDecimal negative = bigDecimal.negate(); // negate keeps scale
System.out.println(negative);
Or the short version:
System.out.println((new BigDecimal(decimal1)).negate());
Find it via String.indexOf('.').
public int findDecimalPlaces (String input) {
int dot = input.indexOf('.');
if (dot < 0)
return 0;
return input.length() - dot - 1;
}
You can also configure a DecimalFormat/ NumberFormat via setMinimumFractionDigits() and setMaximumFractionDigits() to set an output format, rather than having to build the pattern as a string.
int sigFigs = decimal1.split("\\.")[1].length();
Computing the length of the string to the right of the decimal is probably the easiest method of achieving your goal.
If you want decimal places, you can't use floating-point in the first place, as FP doesn't have them: FP has binary places. Use BigDecimal, and construct it directly from the String. I don't see why you need a DecimalFormat object at all.
You could convert a number string to a format string using regex:
String format = num.replaceAll("^\\d*", "#").replaceAll("\\d", "0");
eg "123.45" --> "#.00" and "123" --> "#"
Then use the result as the pattern for a DecimalFormat
Not only does it work, it's only one line.

Is it normal that is not rounding while parsing? NumberFormat

Why does it not round in the parsing process?
NumberFormat format = NumberFormat.getInstance();
System.out.println(format.getMaximumFractionDigits());// 3
System.out.println(format.getRoundingMode());// half even
Double dob = (Double)format.parse("1212.35656");
System.out.println(dob);// output is 1212.35656
The digit counts are only used for formatting. When you parse a number you always get the number that best matches the input, even if it has more digits than the NumberFormat would use to format.
To parse a number from a string and then round to a given number of fractional digits you can use BigDecimal from the java.math package:
BigDecimal bd = BigDecimal("1212.35656");
double dob = bd.setScale(3, RoundingMode.HALF_EVEN).doubleValue();
To obtain what you desire you need to call the formatter metod of the implementation NumberFormat loaded (in your case DecimalFromat); i just added the needed lines at the end and wrapped in a main:
import java.text.NumberFormat;
public class NumberFormatRounding {
public static void main(String[] args) throws Exception{
NumberFormat formatter = NumberFormat.getInstance();
System.out.println(formatter.getMaximumFractionDigits());// 3
System.out.println(formatter.getRoundingMode());// half even
Double dob = (Double) formatter.parse("1212.35656");
System.out.println(dob);// output is 1212.35656
String formattedDob = formatter.format(dob.doubleValue());
System.out.println(formattedDob);// output is 1212.357
}
}
Note that the formattedDob is a String

Categories