How to have percentage as text?

In the aim trainer that I’m making, I want it to show ur accuracy at the end.
heresr the code i have for finishing the game so far

the hittext is the amount of shots hit to amount of shots shot ratio and the accuracy text is the text at the end that says u hit _ out of _ shots.

i have a percentage text but i removed it from the code and disabled it currently.

how do i make it so the percentage text will show the percentage of shots that you hit, out of 100%?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.SceneManagement;

public class FinishMenu : MonoBehaviour
{
    public GameObject finishMenuUI;
    public GameObject crosshair;
    public GameObject hitText;
    public TMP_Text accuracyText;


    public ScoreCounter scoreCounter;

    void Start()
    {
   
    }

    void Update()
    {
    if(Input.GetKeyDown(KeyCode.F))
    {
        if(Input.GetKeyDown(KeyCode.F))
        {
        FinishGame();
        }
    }
    }

    public void FinishGame()
    {
    finishMenuUI.SetActive(true);
    crosshair.SetActive(false);
    hitText.SetActive(false);
    accuracyText.text = scoreCounter.shotsHit + "/" + scoreCounter.shotsFired;

    Time.timeScale = 0;

    Cursor.lockState = CursorLockMode.None;
    Cursor.visible = true;
    }

    public void LevelSelect(string levelSelect)
    {
    Debug.Log("Opening level selector");
    }

    public void Quit(string menuLevel)
    {
    SceneManager.LoadScene(menuLevel);
    }
}

bump pls help

You just could just divide shots hit by shot’s fired and then use the ToString format specifier to convert to a percentage. I’m assuming that scoreCounter.shotsHit and scoreCounter.shotsFired are ints? If that’s the case, then you’ll need to cast them as floats so that decimal division can take place.

So something like this:
((float) scoreCounter.shotsHit / (float) scoreCounter.shotsFired).ToString("P");

Here is a reference about format specifiers:

1 Like

what is the “P” at the end for? percentage?

YES TYSM
one thing tho, theres a space in between the percent and the “%”
how do i prevent this

you can use the .Replace method:

((float) scoreCounter.shotsHit / (float) scoreCounter.shotsFired).ToString("P").Replace(" ", String.Empty);

it says string does not exist in this current context

try string with a small “s”.

if that dosn´t work, you have to store the string into a new variable before.

string percentage = ((float) scoreCounter.shotsHit / (float) scoreCounter.shotsFired).ToString("P");

Do a “Debug.Log(percentage);” after, to see in the log what your string is. If there is again/still a whitespace in the string, the replace method should work:

percentage = percentage.Replace(" ",string.Empty)