1) Convert the float to a string and truncate that
2) Use the decimal.Round method
I've set up a test environment as follows:
private void SpeedTest() { // [Method 1] debugUtilities.StopwatchStart(); float value = 1.0023378734f; for (int i = 0; i < 10000; ++i) { string truncated = StringTools.Truncate(value.ToString(), 4); } debugUtilities.StopwatchStop(); // [Method 2] debugUtilities.StopwatchStart(); for (int i = 0; i < 10000; ++i) { float truncated = (float)decimal.Round((decimal)value, 4); } debugUtilities.StopwatchStop(); }
The ToString() method (method 1) is always faster.
How can I truncate a float faster (in a similar way to method 2) rather than using method 1?
It seems a little odd that converting it to a string is so much quicker.