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

Saturday, August 13, 2022

[FIXED] How to set a rounded value from double number

 August 13, 2022     android, decimal, java, rounding     No comments   

Issue

I'm trying to calculate the average based on user input. Now I've got the basics working. But when i put in numbers that would be 1\3's etc. I get the whole serie of numbers, when that happens I want it rounded of to 1 number. Just like it does with 'normal' numbers like 5.0

Any explanation or tips etc. are welcome!

final TextView averageView = findViewById(R.id.averageView); 
final String averageText = getString(R.string.average); 
final Button calculateButton = findViewById(R.id.calculateAverageButton); 

calaculateButton.setOnClickListener(new View.onClickListener() { 
    @SupressLint("SetTextI18n")                                                     
    public void onClick(View v) { 

        double grade[]  = {Double.parseDouble(((EditText) findViewById(R.id.grade1)).getText().toString()); 
        double weight[] = {Double.parseDouble(((EditText) findViewById(R.id.weight1)).getText().toString()); 
        double weightTotal = weight[0]; double sum = grade[0] * weight[0] 
        double average = sum / weightTotal 
        averageView.setText(averageText + " " + Double.toString(average));

Solution

You can use String.format() to round the number.

String result = String.format("%.2f", your_double_variable);

You can also use DecimalFormat class.

double avg;
DecimalFormat df = new DecimalFormat("#.##");      
ans = Double.valueOf(df.format(avg));


Answered By - karan
Answer Checked By - Senaida (PHPFixing Volunteer)
  • 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