我的計算結果低于樣本值,我必須在不四舍五入的情況下顯示小數點后 2 位。
-0.00123, -2.222154, -23.154, -2.13, -0.10001, -10.0012, -1.0023, 0.23, 0.56474, 1.000, 11.1111, 1.89566
我正在使用十進制格式:0.00 所以,
使用 " 0.00 " 時,其顯示值為 -0.00128 但不顯示為 -2.2386
根據我的需要,哪個應該是正確的十進制格式?我已經瀏覽了這里的檔案:https : //developer.android.com/reference/java/text/DecimalFormat# :~: text=A DecimalFormat comprises a pattern,read from localized ResourceBundle s .
但是,仍然有困惑,所以在這里發布了問題。
uj5u.com熱心網友回復:
您可以使用BigDecimal所需的比例(例如 2)和舍入模式(例如HALF_UP),如下所示:
import java.math.BigDecimal
import java.math.RoundingMode
fun main() {
val roundingMode = RoundingMode.HALF_UP
val doubles: List<Double> = listOf(
-0.00123, -2.222154, -23.154, -2.13, -0.10001, -10.0012,
-1.0023, 0.23, 0.56474, 1.000, 11.1111, 1.89566
)
doubles.map { BigDecimal(it).setScale(2, roundingMode) }.also { println(it) }
// [0.00, -2.22, -23.15, -2.13, -0.10, -10.00, -1.00, 0.23, 0.56, 1.00, 11.11, 1.90]
}
功能更豐富的相同方法(部分函式而不是常量):
val fancyRound: (scale: Int, roundingMode: RoundingMode) -> (Double) -> BigDecimal =
{ scale, roundingMode ->
{ d -> BigDecimal(d).setScale(scale, roundingMode) }
}
fun main() {
...
val myRound = fancyRound(2, RoundingMode.HALF_UP)
doubles.map { myRound(it) }.also { println(it) }
}
uj5u.com熱心網友回復:
你可以試試:
import java.math.RoundingMode;
import java.text.DecimalFormat;
class Scratch {
public static void main(String[] args) {
String srcNumber = "-2.2386";
DecimalFormat formatter = new DecimalFormat("0.00");
formatter.setRoundingMode(RoundingMode.DOWN);
srcNumber = formatter.format(Double.valueOf(srcNumber));
System.out.println(srcNumber);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/408077.html
標籤:
