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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With