Android double numbers formatting issue - java

I have question regarding formatting in Android, I have the following code which format a double number to have 2 number precision only, the code work well when the android device language is English when I change it for example to Arabic the App crash in the last line. when I debugged in both cases (En - Arabic) I found that the double value passed to the function is the same ex: 1.2040
public static Double getRoundedStringValueTo2Precisions(double value){
// TODO: check how we can parse the values where the decimal separator is comma()
DecimalFormat df = new DecimalFormat("#0.##");
return Double.valueOf(df.format(value));
}

Try with x = Math.round(x * 100.00) / 100.00
And don't forhet to parse
double y = Double.parseDouble(z.getText().toString());

I fixed the issue now it works when I change the language device. here is the fix
NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern("#0.##");
String ss = df.format(value);
return Double.valueOf(ss);

Related

Java convert a format.String

I'm still new to Java and I was wondering if there are any ways to format to a double without having it rounded?
Example:
double n = 0.12876543;
String s = String.format("%1$1.2f", n);
If I were to print to the system, it would return the 0.13 instead of the precise 0.12. Now I have thought of a solution but I want to know if there is a better way of doing this. This my simple solution:
double n = 0.12876543;
double n = Double.parseDouble(String.format(("%1$1.2f", n));
Any other thoughts or solutions?
An elegant solution would be to use setRoundingMode with DecimalFormat. It sets the RoundingMode appropriately.
For example:
// Your decimal value
double n = 0.12876543;
// Decimal Formatting
DecimalFormat curDf = new DecimalFormat(".00");
// This will set the RoundingMode
curDf.setRoundingMode(RoundingMode.DOWN);
// Print statement
System.out.println(curDf.format(n));
Output:
0.12
Further, if you want to do additional formatting as a string you can always change the double value into string:
// Your decimal value
double n = 0.12876543;
// Decimal Formatting
DecimalFormat curDf = new DecimalFormat(".00");
// This will set the RoundingMode
curDf.setRoundingMode(RoundingMode.DOWN);
// Convert to string for any additional formatting
String curString = String.valueOf(curDf.format(n));
// Print statement
System.out.println(curString);
Output:
0.12
Please refer similar solution here: https://stackoverflow.com/a/8560708/4085019
As is, rounded to 2 decimals and truncated to 2 decimals :
double n = 0.12876543;
String complete = String.valueOf(n);
System.out.println(complete);
DecimalFormat df = new DecimalFormat("#.##");
String rounded = df.format(n);
System.out.println(rounded);
df.setRoundingMode(RoundingMode.DOWN);
String truncated = df.format(n);
System.out.println(truncated);
it displays :
0.12876543
0.13
0.12
Your example is working correctly in that it is properly rounding the number to 2 decimal places. 0.12876543 properly rounds to 0.13 when rounded to 2 decimal places. However, it seems like you always want to round the number down? If that is the case then you can do something like this...
public static void main(String[] args) throws IOException, InterruptedException {
double n = 0.12876543;
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.DOWN);
String s = df.format(n);
System.out.println(s);
}
This will print out a value of 0.12
Note first that a double is a binary fraction and does not really have decimal places.
If you need decimal places, use a BigDecimal, which has a setScale() method for truncation, or use DecimalFormat to get a String.

Formatting string number into double variable with two number after decimal point

I'm getting from server a string value formatted as follow: 14.5000
I need to create a double variable from it with two number after decimal point: 14.50. I've tried the following:
DecimalFormat df = new DecimalFormat("#,00");
Double priceD = Double.parseDouble((produitParam.item(paramNb).getTextContent()));
String dx = df.format(priceD);
produit.setPrixTtc(Double.valueOf(dx));
And I'm getting 14.5. If I use DecimalFormat("#.00"), it gives me 15...
Someone could help me with that ?
If you want string with precision upto 2 points after decimal you should use
DecimalFormat df = new DecimalFormat("#.00");
you have used "#,00"
',' is used for specifying grouping Separator.
for more information here is the Java Doc of DecimalFormat:
http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
you should look this link.There is a lot of answer your question.
I think.The best answer is DecimalFormat df = new DecimalFormat("#0.00");
for you in link
[how to convert double to 2 number after the dot?

Set the format for the double

How to set the output format lat and lng like this: 0.000000?
double lat = marker.getPosition().latitude;
double lng = marker.getPosition().longitude;
Preferably without converting to a String, so that the output is a double.
No numbers in Java have any kind of output format associated with them. To output them at all, they are converted to a String, even if you call System.out.println(marker.getPosition().latitude).
It is possible to format a double, like any number, but only when converting to a String.
You can use DecimalFormat:
DecimalFormat df = new DecimalFormat("0.000000");
String formattedLat = df.format(marker.getPosition().latitude);
(The 0 is necessary instead of # to make trailing zeroes show up.)
It is also possible to use String.format().
But conversion to a String is necessary if you want to format the number.
You can try this method to round to 6 decimal places using DecimalFormat
double roundDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("0.000000");
return Double.valueOf(twoDForm.format(d));
}
use like:
double lat = roundDecimals(marker.getPosition().latitude);
double lng = roundDecimals(marker.getPosition().longitude);
The link posted by #TronicZomB has more relevant information and is a good read.

Convert a number to 2 decimal places in Java

I want to convert a number to a 2 decimal places (Always show two decimal places) in runtime. I tried some code but it only does, as shown below
20.03034 >> 20.03
20.3 >> 20.3 ( my code only rounds not converts )
however, I want it to do this:
20.03034 >> 20.03
20.3 >> 20.30 (convert it to two decimal places)
My code below:
angle = a variable
angle_screen = a variable
DecimalFormat df = new DecimalFormat("#.##");
angle = Double.valueOf(df.format(angle));
angle_screen.setText(String.valueOf(angle) + tmp);
Any help on how to do this would be great, thanks.
try this new DecimalFormat("#.00");
update:
double angle = 20.3034;
DecimalFormat df = new DecimalFormat("#.00");
String angleFormated = df.format(angle);
System.out.println(angleFormated); //output 20.30
Your code wasn't using the decimalformat correctly
The 0 in the pattern means an obligatory digit, the # means optional digit.
update 2: check bellow answer
If you want 0.2677 formatted as 0.27 you should use new DecimalFormat("0.00"); otherwise it will be .27
DecimalFormat df=new DecimalFormat("0.00");
Use this code to get exact two decimal points.
Even if the value is 0.0 it will give u 0.00 as output.
Instead if you use:
DecimalFormat df=new DecimalFormat("#.00");
It wont convert 0.2659 into 0.27. You will get an answer like .27.
Try this: String.format("%.2f", angle);
Try
DecimalFormat df = new DecimalFormat("#,##0.00");

How to Java String.format with a variable precision?

I'd like to vary the precision of a double representation in a string I'm formatting based on user input. Right now I'm trying something like:
String foo = String.format("%.*f\n", precision, my_double);
however I receive a java.util.UnknownFormatConversionException. My inspiration for this approach was C printf and this resource (section 1.3.1).
Do I have a simple syntax error somewhere, does Java support this case, or is there a better approach?
Edit:
I suppose I could do something like:
String foo = String.format("%." + precision + "f\n", my_double);
but I'd still be interested in native support for such an operation.
You sort of answered your own question - build your format string dynamically... valid format strings follow the conventions outlined here: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax.
If you want a formatted decimal that occupies 8 total characters (including the decimal point) and you wanted 4 digits after the decimal point, your format string should look like "%8.4f"...
To my knowledge there is no "native support" in Java beyond format strings being flexible.
You can use the DecimalFormat class.
double d1 = 3.14159;
double d2 = 1.235;
DecimalFormat df = new DecimalFormat("#.##");
double roundedD1 = df.format(d); // 3.14
double roundedD2 = df.format(d); // 1.24
If you want to set the precision at run time call:
df.setMaximumFractionDigits(precision)
Why not :
String form = "%."+precision+"f\n";
String foo = String.format(form, my_double);
or :
public static String myFormat(String src, int precision, Object args...)
{
String form = "%."+precision+"f\n";
return String.format(form, args);
}
double pi = Math.PI; // 3.141592653589793
int n = 5;
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(n);
System.out.printf(df.format(pi)); // 3.14159
You can set value of n at runtime. Here from the above code given n = 5 will print 3.14159

Categories