2016-07-14 85 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>