why do I get this numberformatexception? [duplicate] - java

Having this error
java.lang.NumberFormatException: For input string: "20,00"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at com.agitech.autofaces.el.FormatUtil.parseDouble(FormatUtil.java:122)
at com.agitech.erp.converter.DoubleConverter.getAsObject(DoubleConverter.java:27)
after reading decimal-separator-in-numberformat this, i try
public class FormatUtil {
public static char ApplicationDecimalSeparator = ',';
public static char SystemDecimalSeparator;
static {
DecimalFormatSymbols symbols= DecimalFormatSymbols.getInstance();
SystemDecimalSeparator = symbols.getDecimalSeparator();
symbols.setDecimalSeparator(ApplicationDecimalSeparator);
}
public final static Double parseDouble(String d){
if (d==null)
return 0.0;
return Double.parseDouble( fixDecimalSeparator(d) );
}
public final static String fixDecimalSeparator(String d){
if (SystemDecimalSeparator==ApplicationDecimalSeparator)
return d;
return d.replaceAll( ""+SystemDecimalSeparator, ""+ApplicationDecimalSeparator);
}
}
finally the SystemDecimalSeparator is already the ',' so why this exception ?
Its probably expecting 20.00 but how to get and fix this separtor ?
Indeed i test and its expectiong "20.00" instead and the default SystemDecimalSeparator is already the ','

You're calling Double.parseDouble, which always uses a dot as the decimal separator - it doesn't use the default locale at all.
Double.parseDouble is documented to behave like Double.valueOf(String), which has documentation including:
To interpret localized string representations of a floating-point value, use subclasses of NumberFormat.

This should work:
NumberFormat f = NumberFormat.getInstance(); // Gets a NumberFormat with the default locale, you can specify a Locale as first parameter (like Locale.FRENCH)
double myNumber = f.parse("20,0").doubleValue(); // myNumber now contains 20

Related

Round up to two places of decimal of java without reassigning to new variable

I have the following code where I need to print value up to two decimal places removing the dot(.) from the number.
How ever sometimes it print up to two and sometimes up to three places off decimal.
public class CheckSubString3 {
public static void main(String[] args) {
Double[] d={134344.00d,234434.08d,234434.02d};
for(int i=0; i<d.length; i++){
System.out.println((d[i])*(25)/100);
System.out.println(parseLonggetFormattedAmount((d[i])*(25)/100));
System.out.println();
}
}
private static String parseLonggetFormattedAmount(double d) {
DecimalFormat format = (DecimalFormat) NumberFormat
.getInstance(new Locale("en", "gb"));
format.setMinimumFractionDigits(2);
FieldPosition f = new FieldPosition(0);
StringBuffer s = new StringBuffer();
String value = format.format(d, s, f).toString().replace(',', ' ')
.replace('.', ' ');
return value.replaceAll(" ","");
}
}
Below is the output:
original value 33586.0
required value 3358600
original value 58608.52
required value 5860852
original value 58608.505
required value 58608505// This line is giving upto 3 places of decimal
According to the NumberFormat documentation, you could use setMaximumFractionDigits(int newValue)
Sets the maximum number of digits allowed in the fraction portion of a number.
just put it in your function parseLonggetFormattedAmount(double d):
format.setMaximumFractionDigits(2);
It seems you simply want to multiply the doubles by 100 and round to the nearest integer. So your method could be written:
private static String parseLonggetFormattedAmount(double d) {
return String.valueOf(Math.round(d * 100));
}
Which outputs:
3358600
5860852
5860851

String to BigDecimal value

Can someone help me getting the exact value to BigDecimal?
My code is as below,
import java.math.BigDecimal;
public class HelloWorld{
public static void main(String []args){
String x="2.7955814565E10";
BigDecimal y=new BigDecimal(x);
System.out.println(y.toPlainString());
}
}
My actual value in the DB is 27955814565.0, a String. I read this string from DB and set it in a bean class where the amt field has type string, using the value "2.7955814565E10". When I try to convert this to a BigDecimal I get 27955814565 instead of 27955814565.0.
Can someone tell me what is the issue because for rest all fields the logic for converting the string value to BigDecimal is working fine and I want the exact value as in DB?
The BigDecimal doesn't infer extra digits in this case.
If the input is
String x = "2.79558145650E10"; // note the extra 0
you get the expected result. You can also add the digit as required.
String x = "2.7955814565E10";
BigDecimal y = new BigDecimal(x);
if (y.scale() < 1)
y = y.setScale(1);
System.out.println(y.toPlainString());
prints
27955814565.0
BTW If your input is
String x = "2.7955814565000E10"; // note the extra 000
the output is
27955814565.000
As you already know, Your String is in scientific notation,
To translate these value into origional BigDecimal or Decimal we need a proper way.
public class Test {
public static void main(String[] args) {
double firstNumber = 12345678;
double secondNumber = 0.000012345678;
String firstNumberAsString = String.format ("%.0f", firstNumber);
String secondNumberAsString = String.format("%.12f",secondNumber);
System.out.println(firstNumberAsString);
System.out.println(secondNumberAsString);
}
}
output will be:
12345678
0.000012345678
You can use Format method as well on BigDecimal to achieve your goal.
DecimalFormat decimalFormat = new DecimalFormat("0.0000000000");

Print a Double as a String with unknown decimal length

I need to print a Double as a String but I don't know how many decimal places there will be and I have to be prepared for as many as possible. Right, now I'm using this ugly solution:
Double dubs = 0.000157;
NumberFormat formatter = new DecimalFormat(
"##.########################################################################################");
System.out.println(formatter.format(dubs));
You can do this with no conversion:
public class codesnippets {
public static void main(String[] args)
{
Double dubs = 0.000157;
System.out.printf("%f", dubs);
}
}
You can also use
Double dubs = 0.000157;
String dubs_format = String.format("%f", dubs);
System.out.println(dubs);
EDIT: Apparently there is a precision loss when using "%f" as a format string. If this is the case for you, use "%.10f"
Try here man. I think this is what you're saying. The answer given at the bottom.
Number of decimal digits in a double
Here is what I meant.
double d= 234.12413;
String text = Double.toString(Math.abs(d));
int integerPlaces = text.indexOf('.');
int decimalPlaces = text.length() - integerPlaces - 1;
Then you just concatenate them
String xmlString = integerPlaces.toString() + "." + decimalPlaces.toString();
This seemed to work based on Steampunkery's idea. The catch was that I needed an actual String which I realize I wasn't clear on.
String dubString= String.format("%f", dubs);
System.out.println(dubString);

Redefine Scanner's not-a-number recognition?

In Java, the class java.util.Scanner provides a convenient way to parse long strings. In my particular case I have to parse a string with many double values, for which I use the nextDouble() method.
Sometimes, my input string contains nan instead of a valid float number. Unfortunately, Scanner only seems to recognize NaN for not-a-number.
Is there any way to teach it to also recognize nan? Maybe by setting a custom Locale with DecimalFormatSymbols.setNaN()?
How about something like this?
private static final Pattern nan =
Pattern.compile("nan", Pattern.CASE_INSENSITIVE);
public static boolean hasNextDouble(Scanner scanner) {
if(scanner == null)
return false;
return scanner.hasNext(nan) || scanner.hasNextDouble();
}
public static double nextDouble(Scanner scanner) {
if(scanner.hasNext(nan)) {
scanner.next();
return Double.NaN;
}
return scanner.nextDouble();
}
One option is setting a custom Locale. Another option is that internally the scanner uses a regular expression to retrieve a double-string and then uses Double.parseDouble to convert it to a double, so you could call Scanner#next(Pattern pattern) using the regular expression defined here except using "nan" instead of "NaN" and then call Double.parseDouble on the returned string.

How to convert a String into percentage value upto 2 decimal places

I have a string whose value will be like '1/3' or '1/2'. It can be even '2/3'. I need to convert it into its equivalent percentage value upto 2 decimal places and again convert it into String.
Is there any java API already present which does it automatically?
Please let me know if you know any optimum solution for this.
below code might resolve this:
import java.util.StringTokenizer;
public class percentage {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String x="2/3";
System.out.println(convert(x));
}
public static String convert(String x){
int num=0;
StringTokenizer s= new StringTokenizer(x, "/");
while(s.hasMoreElements()){
num =Integer.parseInt(s.nextToken())/Integer.parseInt(s.nextToken());
}
return num+"";
}
}
I have wrote a method of my own to resolve this. convert() method would return a String which gives the desirable output.
To convert a double to a percentage String you can use:
double number = ...;
NumberFormat numberFormat = NumberFormat.getPercentInstance();
numberFormat.setMaximumFractionDigits(2);
String formattedString = numberFormat.format(number);
You could create your own method simply splitting string by "/" and then parsing the strings(of array) numerator and denominator into double.

Categories

Resources