Home > database >  How do I write a function in java to return decimals to a given number of places
How do I write a function in java to return decimals to a given number of places

Time:01-20

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.

CodePudding user response:

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.

CodePudding user response:

This, I think, is the recommended solution.

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

CodePudding user response:

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.

CodePudding user response:

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)

  •  Tags:  
  • java
  • Related