[英]Splitting float
I have a float = 1.30452F 我有一个浮点数= 1.30452F
For my WPF UI, I need to split the float into three parts : 对于我的WPF UI,我需要将float分成三个部分:
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.
我运行你的原始代码100万次,并在它上面做了一个计时器,它是〜890ms。 This change drops that down to 328ms.
这种变化降至328毫秒。 A decent improvement.
一个体面的改进。
string myString = myFloat.ToString();
string part1 = myString.Substring(0, 4);
string part2 = myString.Substring(4, 2);
string part3 = myString.Substring(6);
I assume though that you want more than just the first 4 characters for part1. 我假设你想要的不仅仅是part1的前4个字符。 Here's a math version.
这是一个数学版本。 This one runs in 31ms instead.
这个运行在31ms而不是。
float part1 = (int)(myFloat * 100F) / 100F;
int part2 = (int)((myFloat - part1) * 10000F);
int part3 = (int)((myFloat - part1 - (part2 / 10000F)) * 100000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.