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

Wednesday, August 10, 2022

[FIXED] How would I make it so the output will round up to two decimal places?

 August 10, 2022     decimal, java, netbeans     No comments   

Issue

My code here is working fine but whenever I run it, it doesn't seem to round up and I don't know what to add and where to add it.

package com.mycompany.billofsale;

public class Billofsale {
    public static void main(String[] args) {
        double s = 12.49;
        double p = 20.00;
        double t = 0.13;
        double result = s * t;
        double result2 = s + result;
        double result3 = p - (s + result);
        System.out.println("The total is "+s
                + "\n The tax is "+result
                + "\n The total cost with tax is "+result2
                + "\n The change is "+result3);
    }
}

Solution

You need to use DecimalFormat to format all the numbers that you want to print to the decimals that you want.

Try with this code:

double s = 12.49;
    double p = 20.00;
    double t = 0.13;
    double result = s * t;
    double result2 = s + result;
    double result3 = p - (s + result);
    DecimalFormat format = new DecimalFormat(".00");
    format.setRoundingMode(RoundingMode.HALF_UP);
    System.out.println("The total is " + s + "\n The tax is " +format.format(result) + "\n The total cost with tax is " + format.format(result2)
            + "\n The change is " + format.format(result3));


Answered By - Cardstdani
Answer Checked By - Katrina (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

1,204,045

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 © 2025 PHPFixing