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
Related
I am trying to convert a string 32,646,513.32 to a double and then convert it to a string in scientific notation like this 3.264651332E7. The code below is
double amount = 0;
for (Payments payments : pvor.getPayments()) {
payments.setDocumentNumber(pvor);
amount += Double.parseDouble(payments.getAmount());
payments.setDate(new Date());
}
DecimalFormat df = new DecimalFormat("#.00");
double totalAMount = Double.valueOf(df.format(amount));
Double totalAMounts = (Double) totalAMount;
pvor.setAmount(String.valueOf(totalAMounts.doubleValue()));
How do I display large numbers in same format as I give?
Instead of using just String.valueOf(totalAmounts), which give you number in exponential format, you need to format your double value to match the string format that you want. Try something like new DecimalFormat("#,###.00").format(totalAmounts). Or simply use String.format("%,.2f", totalAMounts).
If I understood your problem correctly then you do not need String.valueOf() but String.format().
Here is the code snippet:
public static void main (String[] args) throws Exception
{
String input = "32,646,513.32";
double value = Double.parseDouble(input.replace(",",""));
String output = String.format("%f",value);
System.out.println("Value: " + output);
}
Output:
Value: 32646513.320000
Replace the following line in your code appropriately:
/* Note the change from `valueOf()` to `format()` */
pvor.setAmount(String.format("%f",totalAMounts.doubleValue()));
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
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"
}
}
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;
}
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.