-3

Acually i tried to add two float values in Java like this:

import java.text.DecimalFormat;
class ExactDecimalValue
{        
    final strictfp static public void main(String... arg)
    {    
       float f1=123.00000f;           
       float f2=124.00000f;           
       float f3=f1+f2;

       System.out.println(f1+f2);
       System.out.println("sum of two floats:"+f3);

       /*my expected output is:247.00000
         but comming output is:247.0   and 247*/   
    }     
}

Now what i can do to get the value in this format:247.00000.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
user1845286
  • 1
  • 1
  • 1
  • 2

4 Answers4

2

This will work:

float f1=123.00000f;

float f2=124.00000f;

float f3=f1+f2;

System.out.println(f1+f2);
System.out.printf("%.5f", f3);

Whenever I want to format floats I always use printf.

Ironcache
  • 1,719
  • 21
  • 33
bigfetz
  • 297
  • 1
  • 5
  • 12
1

You can use DecimalFormat class for setting up the precision

float f1=123.00000f;
float f2=124.00000f;
float f3=f1+f2;
DecimalFormat f = new DecimalFormat("0.00000");
System.out.println(f.format(f3));

the output will be 247.00000

Amit Gupta
  • 11
  • 2
0

It's not that the actual addition is wrong, it's just that printing the value out is assuming that you don't need the exact value, in layman's terms... For more information about floating point precision, see: Round-Off Error.

See this answer on specifying decimal output of a float: How to display an output of float data with 2 decimal places in Java?

Ironcache
  • 1,719
  • 21
  • 33
H31IX
  • 113
  • 1
  • 7
-1

Method 1:

Float f3 = Float.sum(f1, f2);

Method 2:

Float f3 = f1.floatValue()+f2.floatValue();
Zoe
  • 27,060
  • 21
  • 118
  • 148
Shyam
  • 185
  • 2
  • 7