otto1
otto1

Reputation: 11

How to add numbers stored in Strings

how do I add Huge Decimal numbers in Java without using the BigDecimal class?

for example

HugeDecimal decimal1 = new HugeDecimal("16878898190.0523515");
HugeDecimal decimal2 = new HugeDecimal("27876186491.0523");

HugeDecimal decimal3 = decimal1.add(decimal2);

I know that you will need to store it in a String and add each digit, I was successful adding two whole numbers but I have no success when it comes to the decimal part. Help!

Here's what I have so far

I split the First Half of the String and the numbers after the decimal.

String string1 = "857267.421847921";
String[] halves = string.split("\\.");
String firstHalf = halves[0];
String secondHalf = halves[1];

I'm still having a hard time on how to lineup the decimals and create padding if the numbers are not equal in length.

Upvotes: 1

Views: 105

Answers (1)

Dev Blanked
Dev Blanked

Reputation: 8865

Just as you're adding the whole numbers, separate out the fraction parts and add them separately. Before adding make sure the two fraction parts are of the same length. Any increase in length after adding means the first digit should be added to the whole part.

two numbers to add -> 10.101 + 2.9
take fraction parts -> 101, 9
make length of fraction parts equal -> 101, 900
add parts -> 101 + 900 = 1001
length has increased from 3 to 4, take digits that caused length increase and add them to the whole parts -> 10 + 2 + 1 = 13
result -> 13.001 (001 taken from addition of fraction parts 1001)

Upvotes: 1

Related Questions