gpt4 book ai didi

java - 在android Java中格式化 float

转载 作者:行者123 更新时间:2023-12-01 10:49:07 24 4
gpt4 key购买 nike

我想按照以下模式将 float 格式化为字符串

X.XX -> 当小数点前只有 1 位数字时,则为 2 位小数精度

XX.XX -> 当小数点前有 2 位数字时,则为 2 位小数精度

XXX.X -> 当小数点前有 3 位数字时,小数点精度为 1

XXXX.. -> 当小数点前有 4 位或更多位时,不应显示小数点

如何在 Java 中执行此操作?

最佳答案

只是使用 Decimal Format 的简单代码可能会有所帮助

float f=  24.56f;//Replace with your float number
int i = (int)f;
if(i<100)
System.out.println(new DecimalFormat("#.##").format(f));//This functions will round the last bits also i.e. greater then 4 will increase the number preceding also
else if( i < 1000)
System.out.println(new DecimalFormat("#.#").format(f));
else
System.out.println(new DecimalFormat("#").format(f));

关于java - 在android Java中格式化 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34019999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com