java - 将 float 格式化为 n 位小数

标签 java android floating-point numbers format

我需要将 float 格式化为“n”个小数位。

正在尝试 BigDecimal,但返回值不正确...

public static float Redondear(float pNumero, int pCantidadDecimales) {
    // the function is call with the values Redondear(625.3f, 2)
    BigDecimal value = new BigDecimal(pNumero);
    value = value.setScale(pCantidadDecimales, RoundingMode.HALF_EVEN); // here the value is correct (625.30)
    return value.floatValue(); // but here the values is 625.3
}

我需要返回一个带有我指定的小数位数的浮点值。

我需要 Float 值返回而不是 Double

.

最佳答案

您也可以传递浮点值,并使用:

String.format("%.2f", floatValue);

Documentation

关于java - 将 float 格式化为 n 位小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5195837/

相关文章:

c++ - 如何将数组 float* 转换为 float**?

floating-point - 基数排序 float 数据

java - Spring-Data-Neo4J:如何保存关系上的属性?

android - phonegap-facebook-插件 : only works when native FB app is not installed (Android)

JavaFX 在网格面板上交换按钮

android - 尝试使用 FragmentActivity 时无法访问 ActivityCompat Api 23

android - 您指定的签名指纹已被另一个 Android OAuth2 客户端使用

javascript - 8.00000000000000100000.toFixed(20) 如何等于 8.00000000000000177636?

java - 使用 google-http-client-xml 解析 xml : parsing xml element content as well as attributes using XmlObjectParser

java - 显示 'Loading'帧直到后台进程完成