Objective C 将 int 转换为 NSString (iPhone)
我有以下代码,旨在将毫秒转换为小时、分钟和秒:
int hours = floor(rawtime / 3600000);
int mins = floor((rawtime % 3600000) / (1000 * 60));
int secs = floor(((rawtime % 3600000) % (1000 * 60)) / 1000);
NSLog(@"%d:%d:%d", hours, mins, secs);
NSString *hoursStr = [NSString stringWithFormat:@"%d", hours];
NSString *minsStr = [NSString stringWithFormat:@"%d", mins];
NSString *secsStr = [NSString stringWithFormat:@"%d", secs];
NSLog(@"%a:%a:%a", hoursStr, minsStr, secsStr);
相当简单。 Rawtime 是一个值为 1200 的 int。输出如下:
0:0:1
0x1.3eaf003d9573p-962:0x1.7bd2003d3ebp-981:-0x1.26197p-698
为什么将 int 转换为字符串会给出如此狂野的数字?我尝试过使用 %i 和 %u,但它们没有任何区别。怎么了?
I have the following code that is meant to convert milliseconds into hours, mins and seconds:
int hours = floor(rawtime / 3600000);
int mins = floor((rawtime % 3600000) / (1000 * 60));
int secs = floor(((rawtime % 3600000) % (1000 * 60)) / 1000);
NSLog(@"%d:%d:%d", hours, mins, secs);
NSString *hoursStr = [NSString stringWithFormat:@"%d", hours];
NSString *minsStr = [NSString stringWithFormat:@"%d", mins];
NSString *secsStr = [NSString stringWithFormat:@"%d", secs];
NSLog(@"%a:%a:%a", hoursStr, minsStr, secsStr);
Fairly straightforward. Rawtime is an int with value 1200. The output is like this:
0:0:1
0x1.3eaf003d9573p-962:0x1.7bd2003d3ebp-981:-0x1.26197p-698
Why is it that converting the ints to strings gives such wild numbers? I've tried using %i and %u and they made no difference. What is happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须使用
%@
作为 NSString 的转换说明符。将最后一行更改为:%a
意味着完全不同的东西。来自printf()
手册页:You have to use
%@
as the conversion specifier for an NSString. Change your last line to:%a
means something totally different. From theprintf()
man page:您应该使用
NSNumberFormatter
用于数字或NSDateFormatter
用于日期/时间。这些数据格式化程序负责将格式本地化为用户的区域设置并处理各种内置格式。为了您的使用,您需要将毫秒时间转换为
NSTimeInterval
(typedef
来自双精度):现在您可以使用
NSDateFormatter
显示时间:在 OS X 上,最后一行删除“AM/PM”。这适用于小于 12 小时的任何时间,并会给出 HH:MM:SS 本地化格式的格式化字符串。在 iPhone 上,
localizedStringFromDate:dateStyle:timeStyle:
尚不可用。您可以在日期格式化程序实例上使用setTimeStyle:
、setDateStyle:
和stringFromDate:
实现相同的效果。Instead of rolling your own string formatting code, you should be using an
NSNumberFormatter
for numbers or anNSDateFormatter
for dates/times. These data formatters take care of localization of format to the user's locale and handle a variety of formats built-in.For your use, you need to convert your millisecond time into an
NSTimeInterval
(typedef
'd from a double):Now you can use an
NSDateFormatter
to present the time:on OS X where the last line removes the "AM/PM". This will work for any time less than 12 hrs and will give a formatted string in the localized format for HH:MM:SS. On the iPhone,
localizedStringFromDate:dateStyle:timeStyle:
isn't available (yet). You can achieve the same effect withsetTimeStyle:
,setDateStyle:
andstringFromDate:
on a date formatter instance.