-1

I am suprise to see the below program please advise how it is behaving like this as i aam very much concerened with poitn to precison after decimal point , below is the progrmam

double fixedRate = 0.997500000000;  //**output --->0.9975
    //  BigDecimal fixedRate = new BigDecimal("0.997500000000");        
        double fixedRate1 = 0.1234567890123456789;  

        System.out.println(fixedRate);
        System.out.println(fixedRate1);

and the output is

0.9975
0.12345678901234568

now please advise for the first the ouput is 0.9975 but late on for next it is not truncating after decimal points but why for first then.

user1508454
  • 301
  • 1
  • 4
  • 16

3 Answers3

0
This is a printing problem.Please use this format to print your values and tell me the result: 

double fixedRate = 0.997500000000;
double fixedRate1 = 0.1234567890123456789; 

System.out.println(String.format("%.19f", fixedRate ));
System.out.println(String.format("%.19f", fixedRate1 ));

Good Luck !
  • @user1508454.. Please use this : System.out.println(String.format("%.19f", fixedRate )); System.out.println(String.format("%.19f", fixedRate1 )); – Serign Modou Bah Sep 23 '16 at 08:38
  • @user1508454 ..it means you should set the deciminal places at your wish. E.g .. %.2f, %3.f , %4.f and for your case I think it is %19.f. – Serign Modou Bah Sep 23 '16 at 08:39
0

The precision is not lost. It is just not printed because you do not need more digits to distinguish the printed value from any other double value.

If you do want to force a certain number of fractional digits, take a look at System.out.printf() or String.format().

See https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html for more details and possible formats.

The result may look like this:

            System.out.printf("%.19f%n",fixedRate);
            System.out.printf("%.19f%n", fixedRate1);
Alexander
  • 1,356
  • 9
  • 16
0

According to your question

for the first the ouput is 0.9975 but late on for next it is not truncating after decimal points but why for first then

Since double is numeric datatype and hence cannot hold the leading and trailing zeros.

A double doesn't care about formatting - it's about storage only. When you print it, it is converted to a String (using Double's static toString method).

In simple terms the value 0.9975 is not different from 0.997500000000or it is same as 0.997500000000 as zeros after a number will not have any value.

But consider if you had value like this 0.9975000000001 then all the numbers will be printed. Check it here.

If you want to format the value then you can see this question : How to properly display a price up to two decimals (cents) including trailing zeros in Java?

Community
  • 1
  • 1
Ravikumar
  • 891
  • 12
  • 22