Monday, October 12, 2015

java - How to convert string to double

MainActivity.java

package com.cfsuman.me.javaexamples;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get widget reference from XML layout
        TextView tv = (TextView) findViewById(R.id.tv);

        // Initialize a new string with double data type value
        String stringOfDoubleValue = "29.99";
        tv.setText("String : " + stringOfDoubleValue);

        // Parse string to double
        double doubleFromString = Double.parseDouble(stringOfDoubleValue);
        tv.setText(tv.getText()+ "\nDouble.parseDouble(): " + stringOfDoubleValue);

        // Another way to convert a string to double
        double value = Double.valueOf(stringOfDoubleValue);
        tv.setText(tv.getText()+ "\n\nString : " + stringOfDoubleValue);
        tv.setText(tv.getText()+ "\nDouble.valueOf() : " + value);

        // Another way to convert a string to double
        double doubleValue = new Double(stringOfDoubleValue).doubleValue();
        tv.setText(tv.getText()+ "\n\nString : " + stringOfDoubleValue);
        tv.setText(tv.getText()+ "\nnew Double().doubleValue() : " + doubleValue);

        // Initialize a new string of double value with comma decimal separator
        String stringAsDouble = "125,33";
        tv.setText(tv.getText()+ "\n\nString : " + stringAsDouble);

        // Another way to convert a string to double using decimal formatter
        DecimalFormat formatter = new DecimalFormat();
        DecimalFormatSymbols symbol = new DecimalFormatSymbols();
        // Specify the decimal separator symbol
        symbol.setDecimalSeparator(',');
        formatter.setDecimalFormatSymbols(symbol);

        // Try to parse the double value
        try{
            double doubleVal = formatter.parse(stringAsDouble).doubleValue();
            tv.setText(tv.getText()+ "\nDecimalFormat.parse().doubleValue() : " + doubleVal);
        }catch (ParseException e)
        {
            e.printStackTrace();
        }
   }
}
More android examples