0

I get an float number as output from an method i want to round it to 7 significant digits.For ex:

if 1.234 output should be 1.234000

if 7.1232478 output should be 7.123248

I tried

sum=sum*1000000/1000000;

System.out.println(Float.toString(sum).substring(0,8));

Is there any better way to do this?

singhakash
  • 7,891
  • 6
  • 31
  • 65
e11438
  • 864
  • 3
  • 19
  • 33
  • 3
    http://stackoverflow.com/questions/12806278/double-decimal-formatting-in-java – DeiAndrei Mar 04 '15 at 11:14
  • The link doesn't specifically mention the rounding issue. The answers there can easily be extended to cover it though, I have added an answer showing the extension – abcdef Mar 04 '15 at 11:32

5 Answers5

2

If you want to display the result, use System.out.printf(".7f"); or String.format(".7f") :

System.out.printf("%.7f\n", 1.123456789123456789);

1.1234568

Is you want to compute something, look at BigDecimal

//For example, divide by 1 and give a prevision of 7 digits
BigDecimal divide = bigDecimal.divide(BigDecimal.ONE, 7, RoundingMode.HALF_EVEN);
System.out.println(divide);

1.1234568

Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
1

The printf has this feature

System.out.printf ("%.7f", floatNumber);
Dragan
  • 455
  • 4
  • 12
1

Use DecimalFormat to format numbers.

DecimalFormat df = new DecimalFormat("####0.000000");
String result = df.format(1.234);
System.out.println(result);

1.234000

Quick Reference link

http://tutorials.jenkov.com/java-internationalization/decimalformat.html

http://examples.javacodegeeks.com/core-java/text/decimalformat/java-decimal-format-example/

1

String class has a format method in it. you can use that.

String number=String.format("%.7f", 1.234567777);

number variable will have desired result i.e. (1.2345678)

1

Step 1, create DecimalFormat (example is number with 7 decimal places, replaces with zeros if smaller than 7)

DecimalFormat df = new DecimalFormat("0.#######");

Step 2, set the rounding mode (chosen mode is just an example, choose one that suits you best)

df.setRoundingMode(RoundingMode.HALF_UP);

Step 3, format number

String myNumber = df.format(1.234);
abcdef
  • 441
  • 3
  • 13