2016-07-14 82 views
0

我試圖搜索這個問題的解決方案,但我不確定如何提出問題。

我要用文字和數字填充一個TextView,並將它設置在一個Activity中。

 float leftTimeSecs = leftTime/1000; 
     float roundedLeftSecs = round(leftTimeSecs, 3); 
     //How to access this directly from "strings" or .xml files 
     duration.setText(getString(R.string.time_data_sec, roundedLeftSecs, 
       getString(R.string.seconds))); 

我的字符串,我設置的文本是:

<string name="time_data_sec">Duration: %1$f %2$s</string> 

,並呼籲全面功能

public static float round(float value, int places) { 
     if (places < 0) throw new IllegalArgumentException(); 
     BigDecimal bigDecimal = new BigDecimal(value); 
     bigDecimal = bigDecimal.setScale(places, RoundingMode.HALF_UP); 
     return bigDecimal.floatValue(); 
    } 

我要打印輸出內容從roundedLeftSecs值(這是leftTime舍入到三個位置),但是當我不硬編碼roundLeftSecs時,它會在舍入後產生很多尾隨零。

我發現%1 $ d是一個小數佔位符,但它不會讓我用float或double表達式,所以我不確定如何擺脫這個零或者甚至可能。

回答

0

對於那些曾經有過同樣問題的人,我使用%1 $ s解決了這個問題,並將我的舍入數轉換爲一個字符串,並且它完美地工作!

這裏就是我想輪:

float leftTimeSecs = leftTime/1000; 
       float roundedLeftSecs = round(leftTimeSecs, 3); 
       String roundedLeftSecString = Float.toString(roundedLeftSecs); 
       duration.setText(getString(R.string.time_data_sec, roundedLeftSecString, 
         getString(R.string.seconds))); 

這裏是字符串:

<string name="time_data_sec">Duration: %1$s %2$s</string>