Convert Double to String Android - java

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

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 to two decimal values after point

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

Why am I getting a IllegalArgumentException in my Android App?

I am working on an Android app, and I am getting the most annoying NFE for, what seems like, no reason.
So, here is what I have in my app:
int amount = 7;
NumberFormat myNumberFormat = NumberFormat.getCurrencyInstance(Locale.US);
TextView money = (TextView)findViewById(R.id.money_view);
money.setText(myNumberFormat.format(amount));
And for some reason, I am getting a NFE when I try to get the NumberFormat currency instance. As a test, to make sure I wasn't going crazy, I also wrote this stand-alone:
import java.util.Locale;
import java.text.NumberFormat;
public class NFETest {
public static void main(String[] args){
int amount = 7;
NumberFormat myNumberFormat = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println(myNumberFormat.format(amount));
}
}
The stand-alone works with no problems. So, what gives ... why am I getting this error?
EDIT:
Looking further down LogCat, it looks like it is an IllegalArgumentException instead of a NFE. However, this doesn't make it any less strange. I have "Locale.US" set, so that shouldn't make any difference. However, some quick googling says it may be my tablet thinking it is not in the US. It may be a hardware issue, and not software after all.
Use this code
int amount = 7;
NumberFormat myNumberFormat = NumberFormat.getCurrencyInstance(Locale.US);
TextView money = (TextView)findViewById(R.id.money_view);
money.setText(String.valueOf(myNumberFormat.format(amount)));
Just use wrappers(Integer, Float, Double, BigDecimal or others):
public static void main(String[] args){
Integer amount = 7;
NumberFormat myNumberFormat = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println(myNumberFormat.format(amount));
int amount2 = 11;
System.out.println(myNumberFormat.format(Integer.valueOf(amount2)));
}
In other solution, you may use Integer.valueOf(..) Look like here: http://ideone.com/0ZKsS3
But your example works too. Look at online compiler: http://ideone.com/0ZKsS3
try {
int amount = 7;
NumberFormat myNumberFormat = NumberFormat.getCurrencyInstance(Locale.US);
TextView money = (TextView)findViewById(R.id.money_view);
money.setText(String.valueOf(myNumberFormat.format(amount)));// your error is here.
//go on as normal
} catch (NumberFormatException e) {
//handle error
}
you should catch the exception and handle the parse error accordingly.
Or you should try for different values :
double num = 1323.526;
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
System.out.println("US: " + defaultFormat.format(num));
Locale swedish = new Locale("sv", "SE");
NumberFormat swedishFormat = NumberFormat.getCurrencyInstance(swedish);
System.out.println("Swedish: " + swedishFormat.format(num));
OUTPUT :
US: $1,323.53
Swedish: 1 323,53 kr
Hope this time it will help you to catch your problem.

NumberFormat : setMaximumFractionDigits - not giving expected results

Trying to figure out why the following code is not outputting expecting results. Please advise. Thank you.
import java.text.*;
public class Test {
public static void main(String[] args) {
String s = "987.123456";
double d = 987.123456d;
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(5);
System.out.println(nf.format(d) + " ");
try {
System.out.println(nf.parse(s));
} catch (Exception e) {
System.out.println("got exc");
}
}
}
Output:
987.12346 // Expected 987.12345 not 987.12346
987.123456
Your second print doesn't format the double you've parsed.
// System.out.println(nf.parse(s));
System.out.println(nf.format(nf.parse(s))); // <-- 987.12346
To get the output you asked for, you can add a call to NumberFormat#setRoundingMode(RoundingMode) - something like
nf.setMaximumFractionDigits(5);
nf.setRoundingMode(RoundingMode.DOWN);

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("#.#");

Categories

Resources