Aya Al-Hussaini
Aya Al-Hussaini

Reputation: 21

How to convert Floating Point into Decimal Java

I would like to write a program that converts a floating point binary number into decimal. I know how to convert a normal binary number into decimal but I would like to convert a floating point binary into decimal with a mantissa of 10 and a exponent of 6.

At the same time I would like to use input to gain the binary value e.g. System.out.println("Enter a binary number"); Then use a scanner to gain input. Is this possible?

Upvotes: 2

Views: 948

Answers (1)

Paul Boddington
Paul Boddington

Reputation: 37645

Given a String like "101011.1011", one approach is:

  1. Split the string into two bits using String.split.
  2. Use the BigInteger constructor BigInteger(String s, int radix) with radix == 2 to get the two BigIntegers representing 1010111011 and 10000.
  3. Use the BigDecimal constructor taking BigInteger to convert to BigDecimal.
  4. Divide the answers.

I don't know if there's a simpler way.

Upvotes: 2

Related Questions