Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm trying to determine the number of digits to the left and the right of the result by...(Java)

Tags:

java

math

using Double.toString(result), indexOf('.') to find the position of the decimal, and length() to find the length. This is what I have so far.

import java.util.Scanner;

public class FormulaEvaluator {

   public static void main(String[] args) {

      double x;
      double discriminant, result;

      Scanner userInput = new Scanner(System.in);
      System.out.print("Enter a value for x: ");
      x = userInput.nextDouble();
      discriminant = 8 * Math.pow(x, 4) - (6 * Math.pow(x, 3)) 
         + +(4 * Math.pow(x, 2)) + Math.abs(20 * x) + 1;
      result = Math.pow(9 * Math.pow(x, 3) + (7 * Math.pow(x, 2)) 
         + +(5 * x) + 3, 2) * Math.sqrt(discriminant); 

      System.out.println("Result: " + result);
   }
}
like image 282
Eric Schwob Avatar asked Feb 01 '26 07:02

Eric Schwob


1 Answers

First get the length of result.

int resultLength = Double.toString(result).length();

Then get the index of the decimal point.

int decimalIndex = Double.toString(result).indexOf('.');

Then subtract the index from the result length to get the number of decimal places after the decimal.

int numPlacesAfterDecimal = resultLength - decimalIndex;

The index of the decimal place happens to be the number of places to the left of the decimal.

int numPlacesBeforeDecimal = decimalIndex;

Edit: Edited variable names for better consistency.

like image 138
david2278 Avatar answered Feb 02 '26 21:02

david2278