简体   繁体   中英

How to get exact value without rounding off

Using java I need to calculate the value for 1/(2^50)

I am getting value as 0.0000000000000008881784197001252

But the exact value is 0.00000000000000088817841970012523233890533447265625

I used power function and divison operator.

you could use the NumberFormat and doing the following:

import java.text.NumberFormat;
NumberFormat nf = NumberFormat.getNumberInstance(); 
nf.setMinimumFractionDigits(0);
nf.setMaximumFractionDigits(5);
System.out.println(nf.format(VariableHere));

this would set the number to have a minimum of 0 decimal places and a maximum of 5 and then print out the re-formatted number.

Very close to this question

    BigDecimal bi1 = new BigDecimal("2").pow(50);
    BigDecimal bi2 = BigDecimal.ONE;

    BigDecimal bi3 = bi2.divide(bi1);
    System.out.println(bi3);

gives output 8.8817841970012523233890533447265625E-16

but if you wont avoid this notation and get pure digits you can add

    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMinimumFractionDigits(0);
    nf.setMaximumFractionDigits(100);
    System.out.println(nf.format(bi3));

and it will give an exact output 0,00000000000000088817841970012523233890533447265625

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM