2017-07-15 69 views
1

我想弄清楚如何输入格式化字符串以在烤面包中使用。吐司使用一个普通的旧字符串,如在烤面包中使用String.format()字符串Android

string s1 = "You scored" 

但它不会与String.format()。为什么是这样?有什么办法可以解决这个问题吗?我已经知道它会工作,如果我做

Toast.makeText(this, "You scored: " + score + "%", Toast.LENGTH_LONG).show(); 

但我想百分比没有任何十进制数。我搜查了四周,但找不到答案。

这是行不通:

float score = ((float) mNumberCorrect/6)*100; 

Toast.makeText(this, String.format("You scored: %d", score) , Toast.LENGTH_LONG).show(); 
+0

查看下面的回答 –

回答

1

你必须写%f代替%d像下面。

float score = ((float) mNumberCorrect/6)*100; 

Toast.makeText(this, String.format("You scored: %f", score) , Toast.LENGTH_LONG).show(); 
+0

哈哈哇,这是一个愚蠢的错误。我认为这与敬酒方法有关。 – Bob

+0

Yeha ...然后请接受答案。 –

0

如果要避免小数点,请尝试使用int代替。您使用%d其表示的整数,而不是浮子

int score = Math.round(mNumberCorrect/6 * 100) 
Toast.makeText(this, String.format("You scored: %d", score) , Toast.LENGTH_LONG).show(); 

注。有关用于不同数据类型的详细信息,请参阅this document

0

IMO你可能会在字符串格式浮点值,然后显示吐司如上

float score = ((float) mNumberCorrect/ 6)*100; 
    String sr = String.valueOf(score); 

    Toast.makeText(this,"You scored: " + sr , Toast.LENGTH_LONG).show(); 
0

你可以简单地这样做:

float score = ((float) mNumberCorrect/6)*100; 

Toast.makeText(this, String.format("You scored: %d %%", score) , Toast.LENGTH_LONG).show(); 

的%%逃脱百分比(%)信并给你想要的输出