Format Float to n decimal places(将浮点数格式化为 n 位小数)
问题描述
我需要将浮点数格式化为n"个小数位.
I need to format a float to "n"decimal places.
正在尝试 BigDecimal,但返回值不正确...
was trying to BigDecimal, but the return value is not correct...
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
}
我需要返回一个带有我指定的小数位数的浮点值.
I need to return a float value with the number of decimal places that I specify.
我需要 Float
值返回而不是 Double
I need Float
value return not Double
.
推荐答案
你也可以传入float值,使用:
You may also pass the float value, and use:
String.format("%.2f", floatValue);
文档
这篇关于将浮点数格式化为 n 位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将浮点数格式化为 n 位小数


- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01