解决方案 如果想法是打印作为双精度数存储的整数,就好像它们是整数一样,否则打印双精度数:public static String fmt(double d){if(d == (long) d)return String.format("%d",(long)d);别的return String.format("%s",d);}产生:2320.1812378751924.5801.2345并且不依赖字符串操作.A 64-bit double can represent integer +/- 2 exactly.Given this fact, I choose to use a double type as a single type for all my types, since my largest integer is an unsigned 32-bit number.But now I have to print these pseudo integers, but the problem is they are also mixed in with actual doubles.So how do I print these doubles nicely in Java?I have tried String.format("%f", value), which is close, except I get a lot of trailing zeros for small values.Here's an example output of of %f232.000000000.180000000001237875192.04.58000000000.000000001.23450000What I want is:2320.1812378751924.5801.2345Sure I can write a function to trim those zeros, but that's lot of performance loss due to string manipulation. Can I do better with other format code?The answers by Tom E. and Jeremy S. are unacceptable as they both arbitrarily rounds to two decimal places. Please understand the problem before answering.Please note that String.format(format, args...) is locale-dependent (see answers below). 解决方案 If the idea is to print integers stored as doubles as if they are integers, and otherwise print the doubles with the minimum necessary precision:public static String fmt(double d){ if(d == (long) d) return String.format("%d",(long)d); else return String.format("%s",d);}Produces:2320.1812378751924.5801.2345And does not rely on string manipulation. 这篇关于如何在没有不必要的十进制 0 的情况下很好地将浮点数格式化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!