Java Float value Formatting with two decimal places - java

Following are my codes to add two values
float ptoTotalAmount = 0;
Map<String, String> renewalDetailview = new LinkedHashMap<String, String>();
String Fee = driver
.findElement(
By.xpath("//div[#data-bind='html: CURRenewalFees']"))
.getText().substring(4).replace(",", "");
ptoTotalAmount += Float.valueOf((ptoFee));
String surcharge = driver
.findElement(By.xpath("//div[#data-bind='html: Surcharges']"))
.getText().substring(4).replace(",", "");
ptoTotalAmount += Float.valueOf((surcharge));
renewalDetailview.put("totalfee", Float.toString(ptoTotalAmount));
For an Example:
Fee - 31500.00,surcharge - 1500.00
Fee + surcharge = 33000.00
Thus, expected result for totalfee - 33000.00, but I'm getting 33000.0
Therefore, I applied Formatting to my float value with 2 decimal places, but I'm not getting expected result.
DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.setMinimumFractionDigits(2);
renewalDetailview.put("totalfee", String.valueOf(df.format(ptoTotalAmount)));
I'm getting 330,00 something like this, please help me to format with 2 decimal places.

It looks like you are trying to model currency.
If so, you should check the answers on this post

Try something like:
float value = 33000.00f;//float??
String formattedString = String.format( "%.2f", value);
System.out.println(formattedString);
Output:
33000.00

Related

Is locale aware parsing for Numberformat possible in Android?

I have an Android application which does some basic mathematics.
Example
try {
NumberFormat nf = NumberFormat.getNumberInstance();
DecimalFormat df = (DecimalFormat) nf;
a = Float.parseFloat(vw3.getText().toString());
f = Float.parseFloat(vw5.getText().toString());
c = a / 100;
d = c * 1.036f;
e = f / 100;
g = e * 1.24f;
h = d + g;
String str1 = String.valueOf(df.format(h));
vw7.setText(str1);
} catch (NumberFormatException f) {
a = (0);
}
}
When the user is in the USA the calculations work fine and format fine. Well as you would expect. The 1,000.00 format where the grouping is by comma and separator is by decimal point. When a user is in France, the grouping is different and the separator is also different. Using the 1,000.00 example, in France the number would be formatted like this 1 000,00. A space is the grouping separator and the comma is the decimal separator. This causes a problem when you try and run a calculation and you will get a NumberFromatException (NFE). And I anticipated a NFE issue and catch it and replace the possible cause with the correct number. However, replacing any comma with a space and any period with a comma will also produce a NFE.
Example
try {
NumberFormat nf = NumberFormat.getNumberInstance();
DecimalFormat df = (DecimalFormat) nf;
a = Float.parseFloat(vw3.getText().toString().replace(",",""));
f = Float.parseFloat(vw5.getText().toString().replace(",",""));
c = a / 100;
d = c * 1.036f;
e = f / 100;
g = e * 1.24f;
h = d + g;
String str1 = String.valueOf(df.format(h));
vw7.setText(str1);
} catch (NumberFormatException f) {
a = (0);
}
}
EDIT - As suggested by Peter O. I have tried parsing the number with a locale aware means.
Example
NumberFormat.getNumberInstance().parse(string);
Or
NumberFormat df = NumberFormat.getNumberInstance();
String value = "10,40 €";
Number valueParsed = df.parse(value);
vw7.setText(valueParsed);
Will produce a "Bad Class" illegalargument.
I am looking for a solution to where I can do the calculations in an acceptable manner within the apps programming regardless of the locale and then later format the results to the locale. The question could be or is, do you force a locale for your calculations and then format the results for the locale?
If this is the code you are using and your strings will have the currency symbol. In this case € the EURO symbol.
Your example:
NumberFormat df = NumberFormat.getNumberInstance();
String value = "10,40 €";
Number valueParsed = df.parse(value);
vw7.setText(valueParsed);
so that value always has a currency symbol you need to use
NumberFormat df= NumberFormat.getCurrencyInstance();
instead of the .getNumberInstance(). This worked on my system which is currently set so that the € symbols is the default currency symbol. You will have to try it on a system that has the $ currency symbol in order to verify that it works there, also.

How to convert string with $ sing in it to int

I have a string "$1,076.00" and I want to convert them in to int,
I capture some value $1,076.00 and saved in string called originalAmount,
and tried int edited = Integer.parseInt(originalAmount); and it gave me error java.lang.NumberFormatException: For input string: "$1,076.00"
can anyone help?
You need to remove the undesired part ($ sign) and then parse the string to double carefully since the decimal part is a locale dependent
String pay = "$1,076.00";
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse(pay.replace("$", ""));
double result = number.doubleValue();
System.out.println(result);
string sourceString = "$1,076.00";
sourceString.substring(1, sourceString.length() - 1)
int foo = Integer.parseInt(sourceString);
Try this:
String amount = "$1,076,.00";
String formatted = amount.replace("$", ""); // remove "$" sign
formatted = formatted.replace(",", ""); // remove "," signs from number
double amountDouble = Double.parseDouble(formatted); // convert to double
int amountInt = (int)amountDouble; // convert double value to int
System.out.println(amountInt); // prints out 1076
String originalAmount="$1076.00";
String amount = originalAmount.replace($,"");
int edited = Integer.parseInt(amount);
Thanks everyone yr answers help me a lot
I have come up with
originalAmount = originalAmount.substring(1);
if (originalAmount.contains("$")) {
originalAmount = originalAmount.replace("$", "");
}
newOriginalAmt = Double.parseDouble(originalAmount);
System.out.println(newOriginalAmt);
pls let me know yr thoughts

Conversion of double to string gives exponent values

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

Convert Strings distance to double in Google map directions

Hello i would like to ask if its possible that the convert the Strings Distance by giving the google map directions and I will convert it to decimal point?
DecimalFormat df = new DecimalFormat("#.##");
Log.e("DISTANCEHECKER", "" + df.format("29 m"));
the 29 will change its depends in google direction result maybe it will change as Km or M it depends. I need to get the exact decimal for this.
Try this out. its a working Code. To Format Your String Distance to any type of unit .....
try{
String distance = "29.336 m"; //Notice that one space between digit and unit.
String arr_distance = distance.split(" "); //split on space
Double digit_distance =Double.parseDouble(arr_distance [0]); // First element as a double to digit.
String unit_distance = arr_distance[1]; // Second Element as String to unit
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(digit_distance);
switch(unit_distance){
case "m":
System.out.println("DISTANCEHECKER" + df.format(digit_distance));
break;
case "km":
System.out.println("DISTANCEHECKER" + df.format(digit_distance*1000));
break;
............
................ //more Code Omitted.as per your requirement
}
}catch(Exception e){
System.out.println(e.getMessage());
}

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"
}
}

Categories

Resources