Convert to two decimal values after point - java

I want to convert 283.8 to 283.80
Used below code but didn't work...plz help
holder.walletBal.setText("$ " +String.format( "%.2f",283.8));

You can use DecimalFormat
Try this
DecimalFormat df = new DecimalFormat("#0.00");
Log.e("ANSWER",df.format(Double.parseDouble("283.8")));
OUTPUT
11-26 11:02:59.021 23883-23883/neel.com.rxjavademo E/ANSWER: 283.80

Please try with below code.
val value = 283.8f
String.format("%.02f", value))

I think it's a good way to put below method in your Utils class. It is working fine.
public static String roundToTwoDigit(Double paramDouble) {
if (!CommonUtils.isTextAvailable(String.valueOf(paramDouble))) return "";
DecimalFormat df = new DecimalFormat("0.00");
String strValue=df.format(paramDouble);
// String doubleValue= String.valueOf(Double.valueOf(strValue));
Log.e("ad","roundToTwoDigit ="+strValue);
return strValue;
}

Related

How to solve the error for DecimalFormat on a calculator app [duplicate]

This question already has answers here:
Problems using DecimalFormat
(6 answers)
Closed 2 years ago.
I am making a calculator app.
workingsTV is the place where calculating is shown.
resultsTV is the place showing the result of calculating.
workings is doing math by using rhino's library.
I want to add a comma at every three digits on both workingsTV and resultsTV.
I tried to use it like this for resultsTV.
DecimalFormat df = new DecimalFormat("###,###.####", new DecimalFormatSymbols(Locale.US));
result = Double.parseDouble(df.format(result));
But then the app was closed when to show result
This is the error message
Caused by: java.lang.reflect.InvocationTargetException
Caused by: java.lang.NumberFormatException: For input string: "1,235"
Here is the top part of the code
public class MainActivity extends AppCompatActivity {
TextView workingsTV;
TextView resultsTV;
String workings = "";
String CLEAR_INT_TEXT;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initTextView();
}
private void initTextView()
{
workingsTV = (TextView)findViewById(R.id.workingsTextView);
resultsTV = (TextView)findViewById(R.id.resultTextView);
}
private void setWorkings(String givenValue)
{
workings = workings + givenValue;
workingsTV.setText(workings);
}
public void equalsOnClick(View view)
{
Double result = null;
ScriptEngine engine = new ScriptEngineManager().getEngineByName("rhino");
try {
result = (Double) engine.eval(workings);
if (result != null)
{
DecimalFormat df = new DecimalFormat("###,###.####", new DecimalFormatSymbols(Locale.US));
result = Double.parseDouble(df.format(result));
int intVal = (int) result.doubleValue();
if (result == intVal)
{//Check if it's value is equal to its integer part
resultsTV.setText(String.valueOf(intVal));
}
else
{
resultsTV.setText(String.valueOf(result));
}
}
}
I'm using that function to convert double to formatted string
public String formatDouble(double value, int digits) {
DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
decimalFormatSymbols.setGroupingSeparator(',');
decimalFormatSymbols.setDecimalSeparator('.');
DecimalFormat decimalFormat = new DecimalFormat("###,##0.00", decimalFormatSymbols);
decimalFormat.setMinimumFractionDigits(digits);
decimalFormat.setMaximumFractionDigits(digits);
return decimalFormat.format(value);
}
In your code, you already have an result value here result = (Double) engine.eval(workings);. Why do you want get it second time? In addition, using formatted string, who may contains illegal character for double (comma char).
Just remove that two lines
DecimalFormat df = new DecimalFormat("###,###.####", new DecimalFormatSymbols(Locale.US));
result = Double.parseDouble(df.format(result));
And format result value when you'll set it to TextView, example with my function:
resultsTV.setText(formatDouble(result, 4));
At the end of equalsOnClick() method, you should set result or intVal to the workings variable to make it ready for next operations.
workings = String.valueOf(result);
Try this:
import java.text.NumberFormat;
import java.util.Locale;
Locale locale = new Locale("en", "US");
NumberFormat fmt = NumberFormat.getCurrencyInstance();
System.out.println(fmt.format(1235.00));

Convert Double to String Android

i try to save my String value (50000000) into Double format, while I'm trying to show it again in my Edittext, I can't to show it in normal format, and it show as (5E+07), is there any way to convert from double format into String format?
I have try this way :
Double value_doble = 5E+07;
EditText.setText(String.valueOf(value_doble);
but its Still show as 5E+07, so my question how to convert from Double to String?
You can try this:
System.out.println(new BigDecimal(value_doble).toString());
Is this what you are looking for?
public static void main(String[] args) {
Double value_doble = 5E+07;
NumberFormat formatter = new DecimalFormat("###.#####");
String f = formatter.format(value_doble);
System.out.println(f);
}
I agree that you need use Formater
http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
but the pattern should be look like this:
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class DoubleFormat {
public static void main(String[] args) {
double valueD = 5E+07;
NumberFormat format = new DecimalFormat("#");
System.out.println(format.format(valueD));
}
}

Doubles, commas and dots

I'm making an Android Java program which is taking double values from the user. If I run the program on the computer, it works great because of the locale of my computer, EN_UK. But when I run it on my mobile phone with FI_FI locale, it won't work. I know the reason: In UK, people use dot as decimal separator but here in Finland, the decimal separator is comma.
DecimalFormat df = new DecimalFormat("#.#");
Double returnValue = Double.valueOf(df.format(doubleNumber));
When I'm using comma, it says java.lang.NumberFormatException: Invalid double: "1234,5".
How can I make it work with them both, comma and dot?
Use one of the other constructors of DecimalFormat:
new DecimalFormat("#.#", new DecimalFormatSymbols(Locale.US))
And then try and parse it using both separators.
using DecimalFormatSymbols.getInstance() will produce the default locale's correct symbols, so you will get it right for any platform you run on.
DecimalFormat df = new DecimalFormat("#.#", DecimalFormatSymbols.getInstance());
This should work for both Java(Tested) as well as android :)
Class Name: In18Helper.java
package com.akmeher.app.utils;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class In18Helper {
private final static In18Helper mHelper = new In18Helper();
public static final In18Helper getInstance() {
return mHelper;
}
public double getDouble(String sValue, Locale locale) {
NumberFormat numberFormat = NumberFormat.getInstance(locale);
Number parse = null;
try {
parse = numberFormat.parse(sValue);
} catch (ParseException e) {
e.printStackTrace();
}
return parse == null ? 0 : parse.doubleValue();
}
}
Class Name: Application.java
package com.akmeher.app;
import java.util.Locale;
import com.akmeher.app.utils.In18Helper;
public class Application {
static DataModel[] testData = new DataModel[] {
new DataModel("1.034567", Locale.ENGLISH),
new DataModel("1,0345.67", Locale.ENGLISH),
new DataModel("1.0345,67", Locale.GERMANY),
new DataModel("1,034,567", Locale.CANADA),
new DataModel("1.034567", Locale.KOREA),
new DataModel("1,03.4567", Locale.ITALY) };
/**
* #param args
*/
public static void main(String[] args) {
for (int i = 0; i < testData.length; i++) {
double d = In18Helper.getInstance().getDouble(testData[i].mValue,
testData[i].mLocale);
System.out.println("Trial Value: "+testData[i].mValue+" for Locale: "+testData[i].mLocale+" converted to: "+d);
}
}
private static class DataModel {
String mValue;
Locale mLocale;
public DataModel(String value, Locale locale) {
this.mLocale = locale;
this.mValue = value;
}
}
}
Output:
Trial Value: 1.034567 for Locale: en converted to: 1.034567
Trial Value: 1,0345.67 for Locale: en converted to: 10345.67
Trial Value: 1.0345,67 for Locale: de_DE converted to: 10345.67
Trial Value: 1,034,567 for Locale: en_CA converted to: 1034567.0
Trial Value: 1.034567 for Locale: ko_KR converted to: 1.034567
Trial Value: 1,03.4567 for Locale: it_IT converted to: 1.03
Hope this will help somebody to make use of.
public static Double parseDoubleTL(String value){
DecimalFormat df = new DecimalFormat("#.#", new DecimalFormatSymbols(new Locale("tr_TR")));
Double doublePrice = 0.0;
try {
doublePrice = df.parse(value).doubleValue();
} catch (ParseException e) {
Log.w(MainActivity.TAG,"Couldnt parse TL. Error is "+e.toString());
}
return doublePrice;
}
Not a best way but worked for me;
Double val=null;
try{
val=Double.valueOf(value);
}catch(Exception e){
val=Double.valueOf(value.replace(',','.'));
}
Double val=null;
try{
val=Double.valueOf(value);
}catch(Exception e){
val=Double.valueOf(value.replace(',','.'));
}
return val;
Me Error:
java.lang.NumberFormatException: Invalid float: "1,683.88"
... and this work for me
replace(",", "")
DecimanFormat df = new DecimalFormat("#.#");

Java serialize double

I want to serialize/deserialize doubles to a readable String. I'm happy to lose any accuracy beyond the 6th dp.
Whats the correct approach for doing this?
I'm concerned about System.out.println(1.03 - .42) printing 0.6100000000000001 and not 0.61.
Thxs.
If you want the value for testing purposes, Double.toString(double) could be good.
If you want a more readable number (1.01 instead of 1.01000000000587732, for example), you can use DecimalFormat (http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html) or BigDecimal:
BigDecimal bd = BigDecimal.valueOf(double)
BigDecimal bd2 = bd.setScale(6, RoundingMode.HALF_UP); // six decimal
String out = bd2.toString();
String out2 = bd2.toPlainString();
Edit: after the user edit, I think a correct approach would be:
DecimalFormat df = new DecimalFormat("0.00");
System.out.println(df.format(1.03 - .42));
Take a look at java.lang.Double.toString() and java.lang.Double.valueOf(String s).
The simplest approach is to use PrintWriter and BufferedReader.
double[][] doubles = new double[10][10];
for(double[] ds : doubles)
for(int i=0;i<ds.length;i++)
ds[i] = Math.random() * 100;
PrintWriter pw = new PrintWriter("double.tsv");
for(double[] ds : doubles) {
for(double d: ds)
pw.printf("%.6f\t", d);
pw.println();
}
pw.close();
BufferedReader br = new BufferedReader(new FileReader("double.tsv"));
String line;
while((line = br.readLine())!=null) {
String[] words = line.split("\t");
for (String word : words) {
double d = Double.parseDouble(word);
System.out.print(d+"\t");
}
System.out.println();
}
prints
72.520491 85.341994 21.958533 48.914986 14.959155 54.398293 54.438528 6.265907 77.654032 94.363109
65.594713 66.943443 69.891651 3.62663 13.445234 3.281239 99.897356 53.072258 11.931774 83.802643
17.387541 56.598334 90.104328 69.379567 95.631605 34.931461 73.336693 21.300139 50.511963 79.326218
61.844333 20.076352 81.668206 69.500067 45.936303 80.639298 86.534122 51.031074 89.718252 89.510961
41.923934 31.450051 35.373463 82.607984 69.796802 11.387551 28.684281 28.524173 3.926274 27.390139
43.116206 81.455006 52.424004 46.399187 84.572294 20.368705 7.414759 18.389408 91.835487 96.594918
87.632357 63.293224 8.751766 70.693449 12.30385 41.090964 93.36716 31.281827 95.411907 29.825814
46.516716 53.442007 18.273036 15.306335 87.773823 72.392803 85.34191 78.388259 80.203328 19.306142
93.249744 50.981212 7.02211 90.461556 46.307283 0.304891 33.055868 98.374818 33.050704 92.423133
41.791121 84.102962 37.881277 80.713237 24.856496 53.619386 99.447379 62.681776 14.927559 37.969094

String to date with no format specified

I want to convert a string into a date, this is simple. But what I'd like to do it without knowing the date format.
Here is a situation: say I have 100 dates and all are in the same format but I'd like to write a Java program to find out this format for me. The result of this program should give me a list of all the possible formats.
For example:
06-06-2006
06-06-2009
...
06-13-2001 <- 99th record
the result of this will give me date format can be mm-dd-yyyy
If the 99th record also was 06-06-2006 the result should be mm-dd-yyyy and dd-mm-yyyy.
Can someone please help me with an example?
Seems sensible to create a set of formats you know about (DATE_FORMATS) and then test each line to see which formats understand every line. You should end up with a set of possibilities.
public class DateFormatDetector {
private static final Set<String> DATE_FORMATS = new HashSet<String>();
static {
DATE_FORMATS.add("yyyy-MM-dd");
DATE_FORMATS.add("dd-MM-yyyy");
DATE_FORMATS.add("MM-dd-yyyy");
}
public static Set<String> getPossibleDateFormats(List<String> dates) {
Set<SimpleDateFormat> candidates = new HashSet<SimpleDateFormat>();
for (String df : DATE_FORMATS) {
SimpleDateFormat candidate = new SimpleDateFormat(df);
candidate.setLenient(false);
candidates.add(candidate);
}
for (String date : dates) {
Iterator<SimpleDateFormat> it = candidates.iterator();
while (it.hasNext()) {
SimpleDateFormat candidate = it.next();
try {
// try to parse the string as a date
candidate.parse(date);
}
catch (ParseException e) {
// failed to parse, so this format is not suitable
it.remove();
}
}
}
Set<String> results = new HashSet<String>();
for (SimpleDateFormat candidate : candidates)
results.add(candidate.toPattern());
return results;
}
}
Try to use SimpleDateFormat prepare all possible formats and calculate parsed result.
The solution could be functional Java as described for example in the stack overflow

Categories

Resources