I'm working with a system that provides me with an int
value which represents 1/10° Celsius. I'd like to format this as a string in °C to display to the user. Basically a function that converts:
int temperature = 2000; // => "200.0"
Is there a built in method for achieving this? My current implementation looks like the following:
private string ConvertToFixedDecimalString(int value, int factorOfTen)
{
var valueString = value.ToString(NumberFormatInfo.CurrentInfo);
if (Math.Abs(factorOfTen) > valueString.Length)
{
valueString = valueString.PadLeft(Math.Abs(factorOfTen) - valueString.Length, '0');
valueString = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator + valueString;
}
else if (factorOfTen > 0)
{
valueString = valueString.PadRight(factorOfTen, '0');
}
else
{
valueString = valueString.Insert(valueString.Length + factorOfTen,
NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);
}
return valueString;
}
Used as:
ConvertToFixedDecimalString(200, -1); // => "20.0"
ConvertToFixedDecimalString(200, -4); // => ".0200"
ConvertToFixedDecimalString(200, 1); // => "2000"
And so on... but this seems to be inelegant and likely to cause issues should I get a NumberFormatInfo that has a group separator.
Additionally, I'm trying to avoid converting to double
via division, since, in the general case, the underlying int
value is exactly precise (from the measurement device) and I don't want to introduce precision errors in the display.