java分区的整数设置精度

ris*_*p89 0 java string

我有两个整数

int a = 5324;
int b = 5;
Run Code Online (Sandbox Code Playgroud)

将"a"除以"b"我应该得到"1064.8"的答案.我想将此答案转换为字符串.我期待我的字符串是"1064.8".我对"8"之后的"."感兴趣.

如何确保我的字符串在"."之后包含正好1个字符.

这是我的尝试:

float answer = ((float) a)/b;
String s = answer.toString();
Character result = s.charAt(s.length()-1);
Run Code Online (Sandbox Code Playgroud)

但是,我无法确保我的结果与"."之后的字符相同.

tha*_*guy 7

您可以将结果乘以10,这样您感兴趣的数字就是整数除法结果中的最后一位数.然后你可以% 10用来得到最后一个10位数:

class Test {
  public static void main(String[] args) {
    int a = 5324;
    int b = 5;

    int fixedpointresult = 10*a/b;
    int lastDigit = fixedpointresult % 10;

    System.out.println(lastDigit);
  }
}
Run Code Online (Sandbox Code Playgroud)

这打印8


Daw*_*per 6

我假设您想以 1 的精度打印结果。 String.format()对此提供支持:

float answer = ((float) a)/b;    
String out = String.format("%.1f",answer);
Run Code Online (Sandbox Code Playgroud)

或者你可以使用 DecimalFormat

  DecimalFormat myFormatter = new DecimalFormat(""###.#"");
  String output = myFormatter.format(value);
Run Code Online (Sandbox Code Playgroud)

其他参考和示例在这里

如果您真的只对.That Other Guys答案后面的第一个字符感兴趣,那么就可以解决问题