如何圆一个双(或字符串)在Java 2位小数? [英] How to round a double (or String) to 2 decimal places in Java?

查看:170
本文介绍了如何圆一个双(或字符串)在Java 2位小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然在StackO。回答很多问题四舍五入,我不能完全把这种对我多部分的问题。 (我不知道为什么在我的后顶部的链接说:答案就在这里......因为这感觉更像是一个资源给我,一说,对于一个初学者来说,是很难去筛选。我不会纷纷拿出psented在我的岗位答案有人$ p $,只是希望通过所有的谈话,并在该网页上分析的链接的RoundingMode。我看到合适的code的一部分是存在的,但前提是人谁知道答案已经向我指出。)

1 我要圆我finalBill TextView的领域,使其为2位小数。我听说过用BigDecimal为好,但不知道怎么写,或者把它放在我的code(我是初学者)。

2 难道是更有智慧舍(我的onClick方法中)双变量,以前我转换为字符串?或者会是更好的四舍五入是在一个字符串传递(在finalBill的TextView场)最终的答案?

现在,我得到了很多很多小数其背后的最终答案。我只需要2。

背景故事:我创建一个小费计算器,当onClick的方法执行每个按钮(10%,15%,20%)...这应该算新的总法案包括尖端,并且也给数字解答在多个不超过2个小数点(它已经被转换为一个TextView)。感谢您的帮助!

这是我的code:我只包括其中第一种方法onTen量,因为这种方法是将前端的计算并在取整需要发生。 (不包括简单起见,其他按钮)。

 包com.example.nonitips;进口java.math.BigDecimal的;
进口java.math.RoundingMode中;进口android.app.Activity;
进口android.os.Bundle;
进口android.view.Menu;
进口android.view.MenuItem;
进口android.view.View;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.TextView;公共类MainActivity延伸活动{    私人的EditText originalBill;
    私人双billWithTip;
    串billString;
    私人TextView的finalBill;
    私人按钮btnTen;
    私人按钮btnFifteen;
    私人按钮btnTwenty;
    双圆= billWithTip;
    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);
        originalBill =(EditText上)findViewById(R.id.originalBill);
    }    公共无效onTen(视图v){
        //Toast.makeText(this,在10%的小费,Toast.LENGTH_SHORT).show();        btnTen =(按钮)findViewById(R.id.btnTen);
        //按钮获取setOnClickListener
        btnTen.setOnClickListener(新View.OnClickListener(){
            @覆盖
            公共无效的onClick(视图v){
                二套= Double.parseDouble(originalBill.getText()的toString());
                billWithTip =比尔* 1.10;
                //打开的答案回字符串
                字符串billString =将String.valueOf(billWithTip);
                finalBill =(的TextView)findViewById(R.id.finalBill);
                finalBill.setText(billString);
            }
        });
    }}


解决方案

对于第一个问题:

1)我建议你使用的方法解释了:

<一个href=\"http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java\">How四舍五入了一些在Java ñ小数。这是很好的解释存在。

和第二个

2)我会亲自刚轮的最终答案。

编辑:经过大量的bug由Dave为指出这是最后code:

相反的声明:

 二套= Double.parseDouble(originalBill.getText()的toString());

您需要编写并添加:

  BigDecimal的法案=新的BigDecimal(originalBill.getText()的toString());
BigDecimal的税=新的BigDecimal(1.10);
BigDecimal的billWithTax = modifiedBill.multiply(含税);
的BigDecimal roundedBill = billWithTax.setScale(2,RoundingMode.HALF_UP);

而在你的code改变下一行:

 字符串billString =将String.valueOf(roundedBill);

此外,你需要导入

  java.math.BigDecimal的;
java.math.RoundingMode中;

另外,请注意,您将不得不改变billWithTax的原先的声明是一个双。

While there are many rounding questions answered in StackO., I could not quite translate this to my multi-part question. (I am not sure why the link at the top of my post says "answer is here"... because this feels more like a resource to me, one that, for a beginner, is very difficult to sift through. I would not have come up with the answer someone presented on my post, just by looking through all of that conversation and analyzing the link for RoundingMode on that page. I see part of the right code is there, but only after it has been pointed out to me by someone who knew the answer.)

1. I need to round my finalBill TextView field so that it is to 2 decimal places. I heard using BigDecimal is good, but don't know how to write it, or where to put it in my code (I am a beginner).

2. Would it be more wise to round the double variable (within my onClick methods), before I convert to a String? Or would it be better to round the final answer that is delivered in a String (in the finalBill TextView field)?

Right now, I get the final answer that has many, many decimals behind it. I just need 2.

Backstory: I am creating a tip calculator, and when the onClick method executes for each button (10%, 15%, and 20%)... this should calculate the new total bill that includes tip, and also give the numeric answer (which has already been converted to a TextView) in a number no more than 2 decimal points. Thanks for your help!

Here is my code: I only included the amount including the first method onTen, since this method is where the tip is calculated and where the rounding needs to happen. (Other buttons not included for simplicity sake).

package com.example.nonitips;

import java.math.BigDecimal;
import java.math.RoundingMode;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    private EditText originalBill;
    private double billWithTip; 
    String billString;
    private TextView finalBill;
    private Button btnTen;
    private Button btnFifteen;
    private Button btnTwenty;
    double rounder = billWithTip;


    @Override
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        originalBill = (EditText)findViewById(R.id.originalBill);
    }

    public void onTen (View v) {
        //Toast.makeText(this, "Tipping at 10%", Toast.LENGTH_SHORT).show();

        btnTen = (Button)findViewById(R.id.btnTen);
        //The button gets the setOnClickListener
        btnTen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                double bill = Double.parseDouble(originalBill.getText().toString());
                billWithTip = bill * 1.10;
                //Turns the answer back into a string
                String billString = String.valueOf(billWithTip);
                finalBill = (TextView)findViewById(R.id.finalBill);
                finalBill.setText(billString);
            }
        }); 
    }

}

解决方案

As for the first question:

1.) I'd suggest you use the method explained in:

How to round a number to n decimal places in Java. It is well explained there.

And the second one:

2.) I would personally just round the final answer.

EDIT: After a lot of bugs as pointed by Dave this is the final code:

Instead of the statement:

double bill = Double.parseDouble(originalBill.getText().toString());

You need to write and add:

BigDecimal bill = new BigDecimal(originalBill.getText().toString());
BigDecimal tax = new BigDecimal("1.10");     
BigDecimal billWithTax = modifiedBill.multiply(tax);
BigDecimal roundedBill = billWithTax.setScale(2,RoundingMode.HALF_UP);

And change the next line in your code to:

String billString = String.valueOf(roundedBill);

Also you will need to import

java.math.BigDecimal;
java.math.RoundingMode;

Also, do note that you would have to change the earlier declaration of billWithTax being a double.

这篇关于如何圆一个双(或字符串)在Java 2位小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆