How round all floats with little script?
Hey everyone, I have a script for rounding floats, but it's getting very long, the more floats I use in my game. Does anyone probably know how to write this piece of code shorter and easier or an exemple on how to write one piece of code that is able to round all these floats?
if (mS.score < 1000.0) { mS.scoreText.text = Mathf.Round(mS.score) + ""; } else
if (mS.score < 1000000.0) { mS.scoreText.text = Mathf.Round(mS.score / 1000) + "K"; } else
if (mS.score < 1000000000.0) { mS.scoreText.text = Mathf.Round(mS.score / 1000000) + "M"; }
if (mS.money < 1000.0) { mS.moneyText.text = Mathf.Round(mS.money * 100) / 100 + ""; } else
if (mS.money < 1000000.0) { mS.moneyText.text = Mathf.Round(mS.money / 1000 * 100) / 100 + "K"; } else
if (mS.money < 1000000000.0) { mS.moneyText.text = Mathf.Round(mS.money / 1000000 * 100) / 100 + "M"; }
if (mS.gems < 1000.0) { mS.gemsText.text = Mathf.Round(mS.gems) + ""; } else
if (mS.gems < 1000000.0) { mS.gemsText.text = Mathf.Round(mS.gems / 1000) + "K"; } else
if (mS.gems < 1000000000.0) { mS.gemsText.text = Mathf.Round(mS.gems / 1000000) + "M"; }
if (mS.mPs < 1000.0) { mS.mPsText.text = Mathf.Round(mS.mPs * 100) / 100 + ""; } else
if (mS.mPs < 1000000.0) { mS.mPsText.text = Mathf.Round(mS.mPs / 1000 * 100) / 100 + "K"; } else
if (mS.mPs < 1000000000.0) { mS.mPsText.text = Mathf.Round(mS.mPs / 1000000 * 100) / 100 + "M"; }
Answer by hexagonius · Dec 08, 2016 at 06:00 PM
I found this challenging and created this method. Maybe there's a smarter way, but this way you can just pass in the value and the the string you want:
static string GetShortenedString(float value){
string seperator = string.Empty;
float divided = value;
while(divided > 1000f){
divided /= 1000f;
seperator += ',';
}
string character = string.Empty;
switch (seperator.Length) {
case 0:
break;
case 1:
character = "T";
break;
case 2:
character = "M";
break;
case 3:
character = "B";
break;
case 4:
character = "T";
break;
case 5:
character = "Q";
break;
}
return value.ToString (("#,##0" + seperator + character), CultureInfo.InvariantCulture);
}
Thank you really much. But it gives an error on CultureInfo, do you know why. And how do I have to replace the coding I had first, because I don't know how to do that.
you need
using System.Globalization;
at the top of the script.
and the you just do
anyTextField.text = theClassWith$$anonymous$$y$$anonymous$$ethod.GetShortenedString(theFloatValue);
Your answer
Follow this Question
Related Questions
How to split a string into multiple floats? 2 Answers
How do i stop Vector3 from rounding? 1 Answer