I have a float = 1.30452F
For my WPF UI, I need to split the float into three parts :
- Part 1 : 1.30
- Part 2 : 45
- Part 3 : 2
A working solution is :
float myFloat = 1.30452F;
string part1 = myFloat.ToString("0.00");
string part2 = myFloat.ToString().Substring(4,2);
string part3 = myFloat.ToString().Substring(6);
Does anyone has a more performant and elegant way of splitting a float ?
A slight improvement (though using the same method) would reduce your string operations. I ran your original code 1 million times and did a timer on it and it was ~890ms. This change drops that down to 328ms. A decent improvement.
I assume though that you want more than just the first 4 characters for part1. Here’s a math version. This one runs in 31ms instead.