Finishing a double while maintaining a trailing zero

Here is my function to round a number to two decimal places, but when the rounded number is 1.50, it seems to ignore the trailing zero and just returns 1.5

public static double roundOff(double number) { double accuracy = 20; number = number * accuracy; number = Math.ceil(number); number = number / accuracy; return number; } 

So if I send 1.499, it will return 1.5, where I want 1.50

+5
source share
4 answers

This is a printed display:

 double d = 1.5; System.out.println(String.format("%.2f", d)); // 1.50 
+10
source

1.5 is the number of significant digits, as well as 1.50 (and even 1.5000000000000 ).

You need to separate the meaning of the number from its representation.

If you want it to be output with two decimal places, just use String.format , for example:

 public class Test { public static void main(String[] args) { double d = 1.50000; System.out.println(d); System.out.println(String.format("%.2f", d)); } } 

which outputs:

 1.5 1.50 

If you still need a function that does all this for you and gives you a specific format, you need to return a string with something like:

 public static String roundOff(double num, double acc, String fmt) { num *= acc; num = Math.ceil(num); num /= acc; return String.format(fmt, num); } 

and name it with:

 resultString = roundOff(value, 20, "%.2f"); // or 100, see below. 

This will allow you to adjust the precision and output format in any way, although you can still hard code the values ​​if you want simplicity:

 public static String roundOff(double num) { double acc = 20; String fmt = "%.2f"; num *= acc; num = Math.ceil(num); num /= acc; return String.format(fmt, num); } 

One final note: your question says that you want to round to β€œtwo decimal places”, but this is not really a gel with your use of 20 as precision, since it rounds it to the next multiple of 1/20. If you really want to round to two decimal places, the value you should use for accuracy is 100 .

+3
source

To do this, you need to format it as a String . Java, like most languages, discards trailing zero.

 String.format("%.2f", number); 

This way you can either return a String (change the return type from double), or simply format it when you need to display it using the code above. You can read the JavaDoc for Formatter to understand all the possibilities with the number of decimal places, commas , etc.

+2
source

You can try this if you want, this is line output

 double number = roundOff(1.499);//1.5 DecimalFormat decimalFormat = new DecimalFormat("#.00"); String fromattedDouble = decimalFormat.format(number);//1.50 

The roundOff function is the same as you mentioned in your question.

0
source

Source: https://habr.com/ru/post/1210628/


All Articles