0

Suppose I have a function double toDecimal(int numerator, int denominator, int places);

How would I write it so that I get the decimal value to the fixed number of places asked for?

 return Math.round((double) numerator * Math.pow(10, places)) /
            (denominator * Math.pow(10, places));

I tried this but on testing even when I add decimals with more places the tests passed when they shouldn't be.

Halil Ozel
  • 2,482
  • 3
  • 17
  • 32
  • 2
    Does this answer your question? [How to round a number to n decimal places in Java](https://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) Read **all** answers. – PM 77-1 Jan 19 '23 at 16:41
  • 1
    A `double` value does not have a specific number of decimal places, at least not a modifiable one. And because few rational numbers are exactly representable as type `double`, your hypothetical value rounded to a certain number of places often cannot be represented as a `double` whose (exact) decimal representation has an all-zero tail starting after the specified number of digits. So what do you *really* want? – John Bollinger Jan 19 '23 at 17:23

4 Answers4

0

You can do this using BigDeciaml class as below:

double rounded = new BigDecimal(double_variable).setScale(3 /*number_of_decimals*/, BigDecimal.ROUND_HALF_UP).doubleValue();

Change second parameter as needed.

0
float f = 1.2232f;
    
int place = 2;
    
String s = String.valueOf(f);
String newS = s.substring(0,s.length() - place);
    
System.out.println(Float.valueOf(newS));

First convert your decimal number in String. Get the substring be eliminating the last values. Convert it back to a decimal number.

fantaghirocco
  • 4,761
  • 6
  • 38
  • 48
Shubham Jain
  • 9
  • 1
  • 1
0

This, I think, is the recommended solution.

   String.format("%.3f", myFloat);
0

You might be trying to do the following:

return Math.round(((double)numerator / denominator) * Math.pow(10,places))
       / Math.pow(10,places);

However, it's not recommended:

  1. The type double represents numbers in base 2, so it cannot precisely store all numbers to base 10; in other words it will store numbers to 3 decimal places only approximately.

  2. Decimal places is something that is only meaningful when you print a number. Therefore, it's better to keep the whole precision and just print out at the end using System.out.printf("%.3f", number)

k314159
  • 5,051
  • 10
  • 32