Home > OS >  How to get rid of zero after decimal point?
How to get rid of zero after decimal point?

Time:11-20

import java.util.Scanner;
import java.lang.Math;

public class Calculator {
  public static void main(String[] args) {
    int firstNum;
    int secondNum;
    int sum;
    int product;
    int difference;
    float division;
    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter First Number : ");
    firstNum = scanner.nextInt();

    System.out.print("Enter Second Number : ");
    secondNum = scanner.nextInt();

    scanner.close();

    sum = firstNum   secondNum;
    difference = firstNum - secondNum;
    product = firstNum * secondNum;
    division = (float) firstNum / secondNum;
    double firstSquare = Math.pow(firstNum, 2);
    double secondSquare = Math.pow(secondNum, 2);

    System.out.println("Sum = "   sum);
    System.out.println("Division = "   division);
    System.out.println("Product = "   product);
    System.out.println("Difference = "   difference);
    System.out
        .println("Square of "   firstNum   " is "   firstSquare   " Square of "   secondNum   " is "   secondSquare);
  }
}

Output

This is a program that takes in two inputs then performs few calculations. I have an issue that I don't want zero after decimal point when I am squaring two inputs. So, how do I get rid of it? Can someone help me with that. Thank you

CodePudding user response:

You can do it with formatting as follows:

System.out.format("Square of %d is %.0f Square of %d is %.0f", 
      firstNum, firstSquare, secondNum, secondSquare);

%d means an integer without decimal places and %.0f means a floating-point number with 0 decimal places as you wanted.

CodePudding user response:

Convert to string and check for ending

public String removePrefix(double number) {
    if(String.valueOf(number).endsWith(".0")) {
        return String.valueOf(number).split(".0")[0];
    }
    return String.valueOf(number);
}

Not tested, but I hope it helps. =)

CodePudding user response:

If you don't want decimals either use an int or cast a double to an int. E.g (int) doubleValue. But if you just want to eliminate the .0 from floating point numbers then perhaps this is what you want.

for (double d : new double[]{2.3, 2.0,1.222, 4445.2, 442.0}) {
    System.out.println(new DecimalFormat("#.######").format(d));
}

prints

2.3
2
1.222
4445.2
442

For more information on the format syntax, check out DecimalFormat

CodePudding user response:

Change the double values firstSquare and secondSquare to ints and cast them to int to change from double that Math.pow() returns to int, no need to round since squares of ints will always be int

int firstSquare = (int) Math.pow(firstNum, 2);
int secondSquare = (int) Math.pow(secondNum, 2);
  •  Tags:  
  • java
  • Related