double变量中的大值在android TextView中显示不同

问题描述 投票:0回答:1

在我的应用中,值如下:

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
java android textview double
1个回答
2
投票

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

    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-硬编码以便于阅读

© www.soinside.com 2019 - 2024. All rights reserved.