Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing first 3 decimal places without rounding

Okay, I know there is a question quite similar already, but it didn't quite answer my question. Please let me know if I'm doing something wrong though.

I have written a program that gets a temperature in Fahrenheit from the user and converts it to Celcius. It looks like this:

import java.util.Scanner;

public class FahrenheitToCelcius {

    public static void main(String[] args) {

        double fahrenheit;
        Scanner sc = new Scanner(System.in);

        System.out.print("Please enter a temperature in Fahrenheit: ");

        fahrenheit = sc.nextDouble();  
        double celcius = (fahrenheit - 32) * 5 / 9;

        String num = String.format("%.3f", celcius);

        System.out.println(" ");
        System.out.println(fahrenheit + "F" + " is " + num + "C");
    } 
}

When it prints the answer out, I want only the first 3 decimal places printed, but not rounded. For example, if the input is 100F, I want 37.777C printed, not 37.778C.

I have tried using DecimalFormat and String.format (like above), but both methods print out 37.778C. Is there a better way to do this?

Thank you for your answers, and I apologise if this is a duplicate.

like image 872
Jaidyn Belbin Avatar asked Nov 28 '22 14:11

Jaidyn Belbin


2 Answers

You can use DecimalFormat, just set the RoundingMode:

DecimalFormat df = new DecimalFormat("#.###");
df.setRoundingMode(RoundingMode.FLOOR);
String num = df.format(celcius);
like image 117
Tagir Valeev Avatar answered Dec 01 '22 03:12

Tagir Valeev


Multiply celsius by 1000 to move the decimal over 3 spots

celsius = celsius * 1000;

Now floor the number and divide by 1000

celsius = Math.floor(celsius) / 1000;    

It will remove the need for the String.format() method.

like image 43
Mahendra Yadav Avatar answered Dec 01 '22 03:12

Mahendra Yadav