【问题标题】:Why am I not getting expected output when using String.format() function? [duplicate]为什么我在使用 String.format() 函数时没有得到预期的输出? [复制]
【发布时间】:2021-05-20 05:06:15
【问题描述】:

为什么我在使用 String.format() 函数时没有得到预期的输出?答案应该是123456789.123456789吧?

main()
{
    float a = 123456789.123456789f; 
    System.out.println(String.format("%f", a));   // Actual Output: 123456792.000000 
    System.out.println(String.format("%.4f", a)); // Actual Output: 123456792.0000 
    System.out.println(String.format("%.4f", a)); // Actual Output: 123456792.0000 
}

【问题讨论】:

  • 除非您告诉我们您的期望,否则我们无法告诉您...
  • 我已经在声明末尾评论了答案,答案不应该是 123456789.123456789

标签: java string.format


【解决方案1】:

浮点数是 32 位的。你刚刚溢出它,它被添加到数字的整数部分

【讨论】:

  • 谢谢!你能告诉我它是如何工作的吗?我的意思是溢出部分是如何添加到整数部分的?
  • 哦,这很肮脏:D 您应该自己在 Oracle 文档 中找到它。对不起。加倍更清楚。但是浮点数有尾数、指数,很难记住它是如何工作的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-08
  • 1970-01-01
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多