PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

[FIXED] How do I convert a double to 2 decimal places?

 August 10, 2022     android, decimal, java     No comments   

Issue

Here is the code: How do I make it come out as only 2 decimal places? My app crashes when I use String.format("%.2f", maltRequiredString);

public class MainActivity extends AppCompatActivity {

    EditText batchVolEditText;
    EditText ogEditText;
    EditText bheEditText;
    TextView maltRequiredTextView;


    public void calculate(View view) {

        String batchVolString = batchVolEditText.getText().toString();
        String ogString = ogEditText.getText().toString();
        String bheString = bheEditText.getText().toString();

        double batchVolDouble = Double.parseDouble(batchVolString);
        double ogDouble = Double.parseDouble(ogString);
        double bheDouble = Double.parseDouble(bheString);
        double specificGravity = 0.96;

        double maltRequired = (batchVolDouble * ogDouble * specificGravity) / bheDouble;


        String maltRequiredString = Double.toString(maltRequired);

        maltRequiredTextView.setText(maltRequiredString + "kg");


    }

Solution

Remember you can't use

 String.format("%.2f", maltRequiredString);

Because maltRequiredString is string. Correct coding is that you must use float in this function and for that you have to convert your string to float

float f = Float.valueOf(maltRequiredString);  
String test = String.format("%.02f", f);

You can also use this technique for making it 2 decimal

DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f));


Answered By - Keyur Nimavat
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing