0

I want a particular number of digits in double/float primitive type. Is there any way to do this?

For example: (fixed to 6 digits)

  1. If we have 12.666666667 gives output as 12.6667
  2. If we have 5.6666666667 gives output as 5.66667
  3. However, if we have 9.00000000 gives output as only 9.*

For, more clear understanding, I have attached an image.enter image description here

How to replicate the same output that I got from below mentioned code in java:

#include<iostream>
using namespace std;
int main()
{
  float num = 9.34333666666663;
  float num2 = 12.0000000
  cout << num;
  cout << num2;
  return 0;
}

Output:-

9.34334
12
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

2 Answers2

0

Two things to consider. One is if you need an exact precision, since floating point arithmetic might not give you that. See the BigDecimal class for more information. The other is what you're trying to do: display a number with a certain number of decimal places. You can accomplish this with String.format. For example

double num = 5.666666666;
String formatted = String.format("%.5f", num);

And

System.out.println(formatted)

Will output

5.66667
geco17
  • 5,152
  • 3
  • 21
  • 38
  • But What if we have 12.6666667 ? Then, the above code will give output as 12.66667 but Output requires as 12.6667(total 6 digits only). And in case of 9.00000000 require only 9 as output. – Ganesh Singh Nov 24 '21 at 09:49
-1
import java.text.DecimalFormat;

public class rounding {
    public static void main(String[] args) {
        double num = 23.122345899;
        double rounded = Math.round(num * 1000000) / 1000000.0;
        System.out.println(rounded);
    }
}
Codemaker2015
  • 12,190
  • 6
  • 97
  • 81