打印小数位左右两侧的数字位数

时间:2014-09-17 00:45:06

标签: java

我无法获得小数点左边的位数。我已经得到了小数点右边的数字并能够打印出来但不能打印到左边。有人可以帮忙吗?

import java.lang.Math;
import java.util.Scanner;
import java.text.DecimalFormat;

public class FormulaCalculation
{
   public static void main(String[] args)
   {
  Scanner userInput = new Scanner(System.in);
  double x;

  //Prompt user for value.
  System.out.print("Enter a value for x: ");
  x = userInput.nextDouble();


  double result = (Math.sqrt(7 * Math.pow(x, 4) - 5 * Math.pow(x, 2) + Math.abs(98 * x)) + 13) * (3 * Math.pow(x, 5) + 4 * Math.pow(x, 3) + 1);
  String resultString = Double.toString(result);


  int integerPlaces = resultString.indexOf('.');
  int digitsLeft = resultString.length();
  int digitsRight = resultString.length() - integerPlaces - 1;


  //Output
  System.out.println("Result: " + result);
  System.out.println("# digits to left of the decimal point: " + digitsLeft);
  System.out.println("# digits to right of the decimal point: " + digitsRight);
  System.out.println("Formatted Result: ");
   }

}

1 个答案:

答案 0 :(得分:0)

打印integerPlaces(您寻找的号码)或将其分配给digitsLeft。像这样的东西,

int integerPlaces = resultString.indexOf('.');
int digitsLeft = integerPlaces; // <-- from 0 to the '.'
    // resultString.length();
int digitsRight = resultString.length() - integerPlaces - 1;

或完全取消digitsLeft

System.out.println("# digits to left of the decimal point: " + integerPlaces);