浮点数,四舍五入到小数点后两位 - 处理

float, round to 2 decimal places - Processing

刚开始学processing,遇到一个问题;当将 199.999 除以 200 我希望结果有 2 位小数 (因此结果应该是 1 舍入)。没有格式化结果是 0.999995.

格式化为带 2 位小数的字符串的代码:

float money = 199.999;
int munten = 200;

String calc1 = nf(money/munten,0,2);
println(calc1);

float calc2 = float(calc1);
println(calc2);

打印:

1,0
NaN

我认为 float() 不会工作,因为字符串中有一个逗号而不是一个点,我不确定很难。但是我怎样才能将一个数字四舍五入到小数点后 2 位,并且仍然让它成为一个浮点数呢?

感谢您花时间阅读本文,

当我 运行 你在 Processing 3.3.6 / macOS 10.12 (US) 上的例子时,我得到“1.00”和“1.0”。这可能是由于您的数字格式设置创建的输出字符串随后无法被 nf().

正确读取
float money;
int munten;
String s;
float f;

money = 199.999;
munten = 200;

s = nf(money/munten, 0, 2);
println(s);   // "1.00" -- or "1,0" etc. in different os language locales
f = float(s);
println(f);   // "1.0" -- or NaN error if above is not 1.0 format

f = money/munten;
println(f);   // 0.999995
s = nf(f, 0, 2);
println(s);   // 1.00 -- or local format

您可以在第二段代码中更清楚地看到应该发生什么 -- 不要尝试转换为 String 然后再退出;不要将数字存储在字符串中。相反,在您需要显示之前,将所有内容都保存在数字变量中。

另请记住,nf() 并非真正用于舍入精度,尽管它经常以这种方式使用:

nf() is used to add zeros to the left and/or right of a number. This is typically for aligning a list of numbers. To remove digits from a floating-point number, use the int(), ceil(), floor(), or round() functions. https://processing.org/reference/nf_.html

如果您需要解决您的语言环境问题,您可以在处理中使用 Java 字符串格式来完成此操作:

float fval = 199.999/200;
println(fval);   // 0.999995
String s = String.format(java.util.Locale.US,"%.2f", fval);
println(s);   // 1.00

有关 Java 方法的更多讨论,请参阅 。