首页 > 解决方案 > 双变量中的大值在 TextView 中显示不同

问题描述

在我的应用程序中有如下值:

double a = 999999999;
double b = 9999999999999999f;
double c = 9876543210987.654321f;

不总是但有时。当我尝试在 textview 中显示它们时,它们的低值数字会发生变化并显示不同的数字。我尝试了很多方法来在 textview 中显示它们,但没有成功。以下是我的所有方法:

double a = 999999999;
double b = 9999999999999999f;
double c = 9876543210987.654321f;

DecimalFormat formatter = new DecimalFormat("#");
TextView tv = findViewById(R.id.tv);

tv.setText(
    String.format("a: %f" , a) + "\n" +
    String.format("b: %f" , b) + "\n" +
    String.format("c: %f" , c) + "\n" +
    "float to string a: " + Double.valueOf(a) + "\n" +
    "float to string b: " + Double.valueOf(b) + "\n" +
    "float to string c: " + Double.valueOf(c) + "\n" +
    "cast a: " + (long)a + "\n" +
    "cast b: " + (long)b + "\n" +
    "cast c: " + (long)c + "\n" +
    "math round a: " + Math.round(a) + "\n" +
    "math round b: " + Math.round(b) + "\n" +
    "math round c: " + Math.round(c) + "\n" +
    "big decimal a: " + new BigDecimal(a).toPlainString() + "\n" +
    "big decimal b: " + new BigDecimal(b).toPlainString() + "\n" +
    "big decimal c: " + new BigDecimal(c).toPlainString() + "\n" +
    "formatted a: " + formatter.format(a) + "\n" +
    "formatted b: " + formatter.format(b) + "\n" +
    "formatted c: " + formatter.format(c) + "\n"
);

下面是输出:

a: 999999999.000000
b: 10000000272564200.000000
c: 9876543635456.000000
float to string a: 9.99999999E8
float to string b: 1.0000000272564224E16
float to string c: 9.876543635456E12
cast a: 999999999
cast b: 10000000272564224
cast c: 9876543635456
math round a: 999999999
math round b: 10000000272564224
math round c: 9876543635456
big decimal a: 999999999
big decimal b: 10000000272564224
big decimal c: 9876543635456
formatted a: 999999999
formatted b: 10000000272564200
formatted c: 9876543635456

标签: javatextviewdouble

解决方案


如果你先转换为字符串,你可以这样做

    System.out.println("big decimal a: " + new BigDecimal("999999999"));
    System.out.println("big decimal b: " + new BigDecimal("9999999999999999"));
    System.out.println("big decimal c: " + new BigDecimal("9876543210987.654321"));

输出

big decimal a: 999999999
big decimal b: 9999999999999999
big decimal c: 9876543210987.654321

NB - 硬编码便于阅读


推荐阅读