- Home /
Dividing On strings CS0019
I want to make a progress percentage, that shows only natural numbers instead of real numbers. so I used the ToString. after that I realized that I cant use operators on strings. so what should I do?
using UnityEngine; using UnityEngine.UI; public class Progress : MonoBehaviour { #region Var public Transform Player; public Text ProgressText; #endregion #region Update //call this function per frame void Update () { ProgressText.text = Player.position.z.ToString("0") / 912.2f * 100f + "%"; } #endregion }
Answer by Bunny83 · Sep 30, 2017 at 09:51 AM
Divide the value before you convert it to a string?
void Update()
{
float v = Player.position.z / 912.2f * 100f;
ProgressText.text = v.ToString("0") + "%";
}
Though keep in mind that the operators /
and *
have equal order so they are evaluated from left to right. So you actually divide by 9.122f
the way you have written your numbers. Though in your case i think that's what you want.
ps: You can use "operators" on strings, but not to perform arithmetic operations. The operators have a different meaning depending on the operands. Custom classes can implement their own operators like Unity's Vector3 struct for example. Of course the string class doesn't have a multiply or divide operator as it wouldn't make any sense. What would be "Hello" * "World"
or "foo" / "bar"
.