从磅转换为公斤时遇到问题
我的应用程序有一个选择器,其中包含后缀为磅的数字。我想添加对用户的支持,以便能够使用 kgs 代替。 所以我尝试使用这个:
NSNumber *weightInPounds = [pickerArray objectAtIndex:row];
NSNumber *weightInKilos = [[DDUnitConverter massUnitConverter] convertNumber: weightInPounds fromUnit: DDMassUnitUSPounds toUnit: DDMassUnitKilograms];
float roundedValue = round(2.0f * [weightInKilos floatValue]) / 2.0f;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:1];
[formatter setRoundingMode: NSNumberFormatterRoundDown];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:roundedValue]];
label.text = numberString;
[formatter release];
使用该代码,它四舍五入到最接近的 .5 或 .0。问题是增量不一致。就像它不是 1, 1.5, 2, 2.5, 3 等。它的结果更像是 1, 2, 3.5, 4.5, 5 等。我认为这是因为当磅转换为公斤时,这就是它的方式出去。但我认为用户不会希望这样显示数字。他们似乎想要 0.5 公斤的正常增量。有谁知道我该如何解决这个问题?
My app has a picker that has numbers with suffix of lbs. I want to add support for user to be able to use kgs instead.
So I tried using this:
NSNumber *weightInPounds = [pickerArray objectAtIndex:row];
NSNumber *weightInKilos = [[DDUnitConverter massUnitConverter] convertNumber: weightInPounds fromUnit: DDMassUnitUSPounds toUnit: DDMassUnitKilograms];
float roundedValue = round(2.0f * [weightInKilos floatValue]) / 2.0f;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:1];
[formatter setRoundingMode: NSNumberFormatterRoundDown];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:roundedValue]];
label.text = numberString;
[formatter release];
Using that code, it rounds to the nearest .5 or .0. The problem is that the increments are not consistent. Like its not 1, 1.5, 2, 2.5, 3, etc. Its coming out more like 1, 2, 3.5, 4.5, 5, etc. I think this is because when lbs are converted to kgs, that is the way it comes out. But I don't think the user will want the numbers displayed like that. It seems like they would want normal increments of .5 kgs. Does anyone know how I can fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您似乎将所有计算都基于选择器的行。如果您想这样做,使拾取器第 1 行(磅)与拾取器第 1 行(千克)重量相同,那么您别无选择,只能这样。更好的解决方案是让轮子从 0 − 300 开始,不带标签。将标签放在其他地方(可能作为旁边的第二个拾取轮或某个开关)。然后您可以获得重量值和单位值并做正确的事情。
更好的是,您可以确定用户的区域设置并自动为其设置单位。
You seem to be basing all of your calculations off of the row of the picker. If you want to do this such that picker row 1 of lbs is the same weight as picker row 1 of kg, then you will have no choice but to have it like this. A better solution is to make the wheel go from 0 − 300 without labels. Put the label somewhere else (perhaps as a second picker wheel next to it or a switch somewhere). Then you can get the value for the weight and the value for the units and do the right thing.
Better yet, you can determine the locale for the user and set the units automatically for them.