Best way to convert Locale specific String to BigDecimal - java

I have to convert a German locale formatted String to a BigDecimal. However, I'm struggling with the best solution.
The following code shows my problem:
String numberString = "2.105,88";
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
try {
Number parsed = nf.parse(numberString);
BigDecimal bd1 = new BigDecimal(parsed.toString());
System.out.println(bd1.toString());
BigDecimal bd2 = new BigDecimal(parsed.doubleValue());
System.out.println(bd2);
BigDecimal bd3 = new BigDecimal(numberString);
System.out.println(bd3);
} catch (ParseException e) {
e.printStackTrace();
}
The outpout of this is
2105.88
2105.8800000000001091393642127513885498046875
Exception in thread "main" java.lang.NumberFormatException
at java.math.BigDecimal.(Unknown Source)
at java.math.BigDecimal.(Unknown Source)
at test.BigDecimalTest.main(BigDecimalTest.java:22)
The first output is correct, but it doesn't really make sense to convert a String to a Number (Double to be precise), then back to a String again and then into a specific type of Number, BigDecimal.
The second output is incorrect, but could be solved by setting the scale of the BigDecimal. However, the amount of digits is not always known.
The third output is obviously not what I'm looking for.
My question: What would be the best way? Are there better ways to do this?

It seems like there is no other way since java.Lang.Number doesn't have a method which returns a BigDecimal type. Anyway it makes sense because BigDecimal only accepts strings which are properly formatted not like "2.105,88" but like "2105.88".
Let me show your my code:
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class JavaMain {
public static void main(String[] args) {
String numberString = "2.105,88";
//using casting
try {
DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN);
df.setParseBigDecimal(true);
BigDecimal bd = (BigDecimal) df.parseObject(numberString);
System.out.println(bd.toString());
} catch (ParseException e) {
e.printStackTrace();
}
//your way short version
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
try {
BigDecimal bd1 = new BigDecimal(nf.parse(numberString).toString());
System.out.println(bd1.toString());
} catch (ParseException e) {
e.printStackTrace();
}
String numberStringFixed = "2105.88";
//direct string formatted
System.out.println(new BigDecimal(numberStringFixed));;
//direct but erroneous way if the string is not formatted
System.out.println(new BigDecimal(numberString));;
}
}
I hope this helps!

DecimalFormat has a method called setParseBigDecimal that causes parse() to return a BigDecimal. You just need to cast the returned Number.
String numberString = "2.105,88";
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
if (nf instanceof DecimalFormat) {
DecimalFormat df = (DecimalFormat) nf;
df.setParseBigDecimal(true);
BigDecimal parsed = (BigDecimal) df.parse(numberString);
System.out.println(parsed);
}
Output:
2105.88
setParseBigDecimal was introduced in Java 1.5.

Related

Parse 2.000,00 to 2000 and 2.000,15 to 2000.15

I am struggling with formatting numbers in java.
My input format looks like this (and I cannot change that): 2.000,15
and the output should look like this: 2000.15
In case of only 0 after the comma the output should look like this: 2000
The input is given as a String.
I've already tried to use a DecimalFormat but this only leads to IllegalArgumentException
DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH);
decimalFormat.setMinimumFractionDigits(0);
decimalFormat.setMaximumFractionDigits(2);
decimalFormat.setGroupingUsed(false);
return decimalFormat.format(Double.parseDouble(characteristicValue));
give this a try:
NumberFormat fmt = NumberFormat.getInstance(Locale.GERMAN);
try {
BigDecimal bd = new BigDecimal(fmt.parse("2.000,15").toString());
System.out.println(bd.toString()); // output: 2000.15
} catch (ParseException e) {
//ex handling
}
You can try the following:
Choose a number format that uses dot-separated thousands-place separators.
Set the minimum significant figures for the decimal (fraction) place.
There is no need to set-up a format that already exists in Java's SDK.
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class FormattingNumbers {
static NumberFormat inputFormat = NumberFormat.getNumberInstance(Locale.GERMAN);
static NumberFormat outputFormat = NumberFormat.getNumberInstance(Locale.US);
static {
inputFormat.setMinimumFractionDigits(2);
outputFormat.setMinimumFractionDigits(2);
}
public static void main(String[] args) throws ParseException {
String[] numbers = { "2.000,00", "2.000,15" };
for (String number : numbers) {
System.out.println(outputFormat.format(inputFormat.parse(number)));
}
}
}
Output:
2,000.00
2,000.15
Note: Here is a list of countries using decimal comma.
You had the right tool, but you don't need to get an instance of DecimalFormat, you can just create your own.
import java.text.DecimalFormat;
class Playground {
public static void main(String[ ] args) {
String pattern = "###,###.###";
DecimalFormat decimalFormat = new DecimalFormat(pattern);
String format = decimalFormat.format(2000.15);
System.out.println(format);
}
}

Format Bigdecimal in Java [duplicate]

This question already has answers here:
Format, 2 decimal places for double and 0 for integer in java
(2 answers)
Closed 6 years ago.
I would like to format a BigDecimal value according to the following rules:
25 => 25
25,1 => 25,10
25,10 => 25,10
25,12 = > 25,12
I have searched the forums but not found a matching question (here, here and here) and I have looked at the javadoc for BigDecimal and NumberFormat without understanding how to do this.
EDIT:
Today I do:
NumberFormat currencyFormat02 = NumberFormat.getCurrencyInstance(locale);
currencyFormat02.setMinimumFractionDigits(0);
currencyFormat02.setMaximumFractionDigits(2);
currencyFormat02.setGroupingUsed(false);
BigDecimal bd = new BigDecimal("25 or 25,1 or 25,10 or 25,12");
String x =currencyFormat02.format(bd);
x should print as above but does not.
Probably not the most efficient but you could try something like this:
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
class Main {
public static void main(String[] args) {
BigDecimal ex1 = new BigDecimal("25");
BigDecimal ex2 = new BigDecimal("25.1");
BigDecimal ex3 = new BigDecimal("25.10");
BigDecimal ex4 = new BigDecimal("25.12");
printCustomBigDecimalFormat(ex1);
printCustomBigDecimalFormat(ex2);
printCustomBigDecimalFormat(ex3);
printCustomBigDecimalFormat(ex4);
}
public static void printCustomBigDecimalFormat(BigDecimal bd) {
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault());
symbols.setDecimalSeparator(',');
DecimalFormat df = new DecimalFormat("##.00", symbols);
if(containsDecimalPoint(bd)) {
System.out.println(df.format(bd));
} else {
System.out.println(bd);
}
}
private static boolean containsDecimalPoint(BigDecimal bd) {
return bd.toString().contains(".");
}
}
Output:
25
25,10
25,10
25,12
Try it here!
You then need to distinguish between BigDecimal values that represent "whole numbers"; and those that do not.
Something like:
BigDecimal someNumber = ...
if (someNumber.toBigIntegerExact()) {
// go for the 25 kind of formatting
} else {
// go for the 25.xx kind of formatting
The "25.xx" formatting is nicely described here ( or in the other answer by Leonardo )
To format BigDecimal with NumberFormat, you need to set Locale first, try something like this:
String strToFormat = "25.10";
Locale loc = new Locale("en","US");
DecimalFormat numFormat = (DecimalFormat)NumberFormat.getInstance(loc);
numFormat.setParseBigDecimal(true);
BigDecimal yourValue = (BigDecimal)numFormat.parse(strToFormat, new ParsePosition(0));
System.out.println("Value : " + yourValue);
Result :
Value : 25.10

String to double and using IsNaN

I have a variable defined as String,
String totalweight;
This might take values '0.00','0.12'...any deciamls and also will have 'n/a' occasionally.
Now I have to format this field in such a way that if its not a number eg: 'n/a' leave it as such else format them like below.
public String getFmtWeight()
{
NumberFormat nf = NumberFormat.getNumberInstance();
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern("#0.00");
if(Double.isNaN(Double.parseDouble(totalweight)))
return totalweight;
else
return df.format(Double.parseDouble(totalweight));
// if(!totalweight.equals("n/a"))
// return df.format(Double.parseDouble(totalweight));
// else
// return "n/a";
}
This is breaking when n/a is cast to double throws exception. However commented portion would work. But I do not want to use it since 'n/a' may change in future with different string. Is there anyother way to achieve the same ?
One solution would be to use a try-catch to account for when parsing the string as a double fails, e.g.:
public String getFmtWeight()
{
NumberFormat nf = NumberFormat.getNumberInstance();
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern("#0.00");
try {
if(Double.isNaN(Double.parseDouble(totalweight)))
return totalweight;
else
return df.format(Double.parseDouble(totalweight));
} catch ( NumberFormatException ex ) {
/* thrown when the String can't be parsed as a double */
return totalweight; // if 'totalweight' is the String you want to parse
}
}
This will handle any string that cannot be parsed into a double using parseDouble.
You can use regular expression to validate.
NumberFormat nf = NumberFormat.getNumberInstance();
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern("#0.00");
String totalweight = "n/a";
String pattern = "[0-9]*.[0-9]*";
boolean isNan = Pattern.matches(pattern, totalweight);
if(!isNan) {
System.out.println(totalweight);
}
else {
System.out.println(df.format(Double.parseDouble(totalweight)));
}
You can try this code

Formating a number to two decimals without rounding up and converting to Double

I know this has been questioned alot of times but i tried all solutions in other threads and i cant find one that matches what i want ...
So i have one input something like this -9.22841 which is read as a String, what i want to do is to format this number to two decimals like this -9.23 without rounding it up and then converting it to double without losing this format...
I have tried many ways like String.format("%.2f",number) and the one below ...
String l = -9.22841
DecimalFormat df = new DecimalFormat("#,00");
String tmp =df.format(l);
double t = Double.parseDouble(tmp);
and this one:
String l = -9.22841
DecimalFormat df = new DecimalFormat("#.00");
String tmp =df.format(l);
double t = Double.parseDouble(tmp);
but everytime i try to convert to double in the String.format("%.2f",number) or DecimalFormat df = new DecimalFormat("#.00"); gives error converting to double
and when i do this :
DecimalFormat df = new DecimalFormat("#,00");
The output is wrong and is something like this -9.23 where it should be -9.22
Thanks for your time ...
You could just chop off the String two spaces after the decimal:
String number = "-9.22841";
String shorterNumber = number.substring(0, number.indexOf(".")+3);
double t = Double.parseDouble(shorterNumber);
System.out.println(t);
Thats what you want:
String number = "-9.22841";
DecimalFormat formatter = new DecimalFormat("0.00");
formatter.setRoundingMode(RoundingMode.DOWN);
number = formatter.format(Double.valueOf(number));
System.out.println(number);
The output will be:
-9,22
You can use bellow function:
import java.text.DecimalFormat;
import java.math.RoundingMode;
public static double formatValue(Double number) {
DecimalFormat df = new DecimalFormat("####0.00");
df.setRoundingMode(RoundingMode.DOWN);
return Double.parseDouble(df.format(number));
}
Input = 31.6227890 ,
OutPUT = 31.62
For someone looking full decimal handling:Kotlin
fun validateNumber(number: String): String {
return if (number.contains(".") && number.length > 3+number.indexOf("."))
number.substring(0, number.indexOf(".")+3)
else if (number.contains(".")){
number.substring(0, number.indexOf(".")+2)+"0"
}else{
"$number.00"
}
}

Why does DecimalFormat allow characters as suffix?

I'm using DecimalFormat to parse / validate user input. Unfortunately it allows characters as a suffix while parsing.
Example code:
try {
final NumberFormat numberFormat = new DecimalFormat();
System.out.println(numberFormat.parse("12abc"));
System.out.println(numberFormat.parse("abc12"));
} catch (final ParseException e) {
System.out.println("parse exception");
}
Result:
12
parse exception
I would actually expect a parse exception for both of them. How can I tell DecimalFormat to not allow input like "12abc"?
From the documentation of NumberFormat.parse:
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.
Here is an example that should give you an idea how to make sure the entire string is considered.
import java.text.*;
public class Test {
public static void main(String[] args) {
System.out.println(parseCompleteString("12"));
System.out.println(parseCompleteString("12abc"));
System.out.println(parseCompleteString("abc12"));
}
public static Number parseCompleteString(String input) {
ParsePosition pp = new ParsePosition(0);
NumberFormat numberFormat = new DecimalFormat();
Number result = numberFormat.parse(input, pp);
return pp.getIndex() == input.length() ? result : null;
}
}
Output:
12
null
null
Use the parse(String, ParsePosition) overload of the method, and check the .getIndex() of the ParsePosition after parsing, to see if it matches the length of the input.

Categories

Resources