簡體   English   中英

在Android Java中格式化浮點數

[英]Formatting Floating point numbers in android Java

我想按照以下模式將浮點數格式化為字符串

X.XX >當小數點前只有1位數字,然后小數點后2位精度

XX.XX >當小數點前有2位數字,則小數點后2位

XXX.X >如果十進制前有3位數字,則精度為1位小數

XXXX.. >如果小數點前有4個或更多數字,則不應顯示小數點

如何用Java做到這一點?

使用十進制格式的簡單代碼可能會有所幫助

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));

假設你有漂浮F

float f;
int a = (int) f;
String res = null;
if (a<100) res = String.format("%.2f");
else if (a<1000) res = String.format("%.1f");
else res = String.valueOf(a);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM