Bryant
Bryant

Reputation: 21

Using String.format() string in a toast Android

I am trying to figure out how to input a formatted string to use in a toast. The toast works with a plain old string, such as

string s1 = "You scored"

But it will not work with String.format(). Why is this? Is there any way to work around this? I already know it will work if I do

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

But I want the percentage to not have any decimal numbers. I have searched around but could not find an answer.

This is what doesn't work:

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

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

Upvotes: 3

Views: 11598

Answers (4)

Bharat
Bharat

Reputation: 1082

You can simply do this :

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

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

The %% escapes the percentage (%) letter and gives you the desired output

Upvotes: 2

Omkar
Omkar

Reputation: 3100

IMO you may get float value in string format and then show in Toast as above

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

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

Upvotes: 0

Software2
Software2

Reputation: 2748

If you want to avoid decimal points, try using an int instead.

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

Note that you were using %d which denotes an integer, rather than a float. See this document for details on what to use for different data types.

Upvotes: 0

Mehul Kabaria
Mehul Kabaria

Reputation: 6622

you have to write %f in place of %d like below.

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

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

Upvotes: 7

Related Questions