如何限制处理中的小数精度?

时间:2012-03-09 00:24:10

标签: java processing

我在处理时有几个浮点值,小数位数超过8位。

在使用text()绘制它们之前,如何将这些值舍入到十分之一?

3 个答案:

答案 0 :(得分:5)

您可以将浮点(floatdoublex格式化为2位小数,如下所示:

String.format("%.2f", x)

这会给你一个String

例如:

String.format("%.2f", 12.34567)

返回字符串"12.35"

答案 1 :(得分:4)

使用http://processing.org/reference/nf_.html中描述的nf功能。 “right”参数允许您指定要使用的小数位数。

编辑:我意识到我误解了你的问题;我上面链接的函数将截断,而不是舍入。一个快速的谷歌给了我以下答案:

float round(float number, float decimal) {
    return (float)(round((number*pow(10, decimal))))/pow(10, decimal);
} 

用户Markavian在此处的帖子中建议:http://processing.org/discourse/yabb2/YaBB.pl?num=1115073288

希望这有帮助。

答案 2 :(得分:1)

你也可以使用DecimalFormat。

DecimalFormat myFormatter = new DecimalFormat("#.##");
String output = myFormatter.format(12.34567);

Check this at docs.oracle.com