- Home /
Floor/Ceiling a decimal with a string c#
I know there is a way to round a decimal by using "#.###", but is there a way I can floor or ceiling a decimal the same way? If there isn't, is there a way I can do it without basically re-writing my whole code?
if (index == 10) {
roundDecimalBool [index] = true;
decimalText.text = "Where applicable, numbers round to the 9th decimal place.";
decimalPlaces = "#.#########";
}
an example of how I set how many places to round the decimal
else if (boolManager.angleBoolsOne [15] == true && boolManager.angleBoolsTwo [16] == true) { /* Arcminute to Arcsecond */
float x;
float.TryParse (manager.inputOne.text, out x);
manager.valueTwoText.text = (x * 60).ToString (manager.decimalPlaces);
an example of where I use the variable I set in the pervious code to round the number
I'd like to do this, but inside of rounding, either flooring or ceiling.
Answer by Bunny83 · Dec 16, 2016 at 10:26 PM
If i understood your question right you just want to either floor or ceil a float value to a certain amount of digits behind the decimal point. The general way to do this is to:
multiply your value by ten to the power of your desired digits
ceil / floor the result
divide the result by the same amount as in step 1.
For example:
public static float Floor(float aValue, int aDigits)
{
float m = Mathf.Pow(10,aDigits);
aValue *= m;
aValue = Mathf.Floor(aValue);
return aValue / m;
}
public static float Ceil(float aValue, int aDigits)
{
float m = Mathf.Pow(10,aDigits);
aValue *= m;
aValue = Mathf.Ceil(aValue);
return aValue / m;
}
When you use Floor(50.123456f, 4) it will return 50.1234.
When you use Ceil(50.123456f, 4) it will return 50.1235.
If that's not what you want to do, you should be more specific. Is this question just about string formatting or do you actually want to floor / ceil the value to a certain point?
Your answer