简体   繁体   中英

Decimal place on a Double TextView

Hi I'm new to Java Programming and I need some help. I'm making a calculation app and I'm struggling with how to use decimals with textview in my results page. Could anyone help

My code:

            double result1 = num1 + num2;
            double result2 = num1 / num2;
            double result3 = num1 * num2;


            setContentView(R.layout.activity_result);

            TextView plusResult = (TextView)findViewById(R.id.plus_result);
            plusResult.setText(Double.toString(result1));

            TextView divResult = (TextView)findViewById(R.id.div_result);
            divResult.setText(Double.toString(result2));

            TextView timesResult = (TextView)findViewById(R.id.times_result);
            timesResult.setText(Double.toString(result3));

            break;

Based on your comments, you want to limit the answer to two decimal places. The following change does this:

double result1 = Math.round((num1 + num2) * 100.0) / 100.0;
double result2 = Math.round((num1 / num2) * 100.0) / 100.0;
double result3 = Math.round((num1 * num2) * 100.0) / 100.0;

It would be better to add a helper function to round if you do this in many places throughout your application.

If you want to round to two decimal places, you could create a method like so:

private double round(double value){
    return  (Math.round(value * 100.0) / 100.0);
}

Multiply it by 100, round to a whole number, then divide by 100 to get exactly 2 decimal places. If you need more or less decimal places, you can change the 100's to different powers of 10.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM