Convert float 1.88 to string HH:MM - ios

I wish to display HH:MM at a UILabel when I adjust a custom slider. Currently my custom slider is returning me float values, for example, 2.89, 24.87... I wish to take the float value say 24.87 and change it to 24:52 I got everything working at the following code but I think it is not the most efficient way. Can anyone improve it? Thank you
- (void)slideValueChanged:(id)control
{
NSLog(#"Slider value changed: (%.2f,%.2f)",
_rangeSlider.lowerValue, _rangeSlider.upperValue);
lblStart.text = [NSString stringWithFormat:#"Start Time : %#", [self floatToTime:_rangeSlider.lowerValue]];
lblEnd.text = [NSString stringWithFormat:#"End Time : %#",[self floatToTime:_rangeSlider.upperValue]];
}
- (NSString*)floatToTime:(float)floatTime {
NSInteger iHour = floatTime;
CGFloat floatMin = floatTime - iHour;
NSString *sHour = [NSString stringWithFormat:#"%li", (long)iHour];
if (floatMin == 0.99) { //=== When the float is 0.99, convert it to 0, if not 60*0.99 = 59.4, will never get to 0
floatMin = 0;
}else{
floatMin = floatMin * 60;
}
NSInteger iMin = floatMin; //=== Take the integer part of floatMin
NSString *sMin = [[NSString alloc] init];
if (iMin <10){ //=== Take care if 0,1,2,3,4,5,6,7,8,9 to be 00,01,02,03...
sMin = [NSString stringWithFormat: #"0%li", iMin];
}else{
sMin = [NSString stringWithFormat: #"%li", iMin];
}
NSString *strFloatTime = [NSString stringWithFormat:#"%#:%#", sHour,sMin];
return strFloatTime;
}

You can use a format to show two digits, this simplifies creating a time string:
CGFloat time = 24.87;
int hours = fabs(time);
int minutes = (int)((time - hours) * 60.0);
NSLog(#"Time: %02d:%02d", hours, minutes);
Result: "Time: 24:52"
'02' is the number of digits.

Related

How to convert this value into absolute value?

I am getting this from webservice
"rateavg": "2.6111"
now i am getting this in a string.
How to do this that if it is coming 2.6 it will show 3 and if it will come 2.4 or 2.5 it will show 2 ?
How to get this i am not getting. please help me
Try This
float f=2.6;
NSLog(#"%.f",f);
Hope this helps.
I come up with this, a replica of your query:
NSString* str = #"2.611";
double duble = [str floatValue];
NSInteger final = 0;
if (duble > 2.5) {
final = ceil(duble);
}else{
final = floor(duble);
}
NSLog(#"%ld",(long)final);
So it a case of using either ceil or floor methods.
Edit: Since you want it for all doubles:
NSString* str = #"4.6";
double duble = [str floatValue];
NSInteger final = 0;
NSInteger temp = floor(duble);
double remainder = duble - temp;
if (remainder > 0.5) {
final = ceil(duble);
}else{
final = floor(duble);
}
NSLog(#"%ld",(long)final);
check this
float floatVal = 2.6111;
long roundedVal = lroundf(floatVal);
NSLog(#"%ld",roundedVal);
plz use this
lblHours.text =[NSString stringWithFormat:#"%.02f", [yourstrvalue doubleValue]];
update
NSString *a =#"2.67899";
NSString *b =[NSString stringWithFormat:#"%.01f", [a doubleValue]];
// b will contane only one vlue after decimal
NSArray *array = [b componentsSeparatedByString:#"."];
int yourRating;
if ([[array lastObject] integerValue] > 5) {
yourRating = [[array firstObject] intValue]+1;
}
else
{
yourRating = [[array firstObject] intValue];
}
NSLog(#"%d",yourRating);
Try below code I have tested it and work for every digits,
NSString *str = #"2.7";
NSArray *arr = [str componentsSeparatedByString:#"."];
NSString *firstDigit = [arr objectAtIndex:0];
NSString *secondDigit = [arr objectAtIndex:1];
if (secondDigit.length > 1) {
secondDigit = [secondDigit substringFromIndex:1];
}
int secondDigitIntValue = [secondDigit intValue];
int firstDigitIntValue = [firstDigit intValue];
if (secondDigitIntValue > 5) {
firstDigitIntValue = firstDigitIntValue + 1;
}
NSLog(#"final result : %d",firstDigitIntValue);
Or another solution - little bit short
NSString *str1 = #"2.444";
float my = [str1 floatValue];
NSString *resultString = [NSString stringWithFormat:#"%.f",my]; // if want result in string
NSLog(#"%#",resultString);
int resultInInt = [resultString intValue]; //if want result in integer
To round value to the nearest integer use roundf() function of math.
import math.h first:
#import "math.h"
Example,
float ValueToRoundPositive;
ValueToRoundPositive = 8.4;
int RoundedValue = (int)roundf(ValueToRoundPositive); //Output: 8
NSLog(#"roundf(%f) = %d", ValueToRoundPositive, RoundedValue);
float ValueToRoundNegative;
ValueToRoundNegative = -6.49;
int RoundedValueNegative = (int)roundf(ValueToRoundNegative); //Output: -6
NSLog(#"roundf(%f) = %d", ValueToRoundNegative, RoundedValueNegative);
Read doc here for more information:
http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/roundf.3.html
NSString *value = #"1.23456";
float floatvalue = value.floatValue;
int rounded = roundf(floatvalue);
NSLog(#"%d",rounded);
if you what the round with greater value please use ceil(floatvalue)
if you what the round with lesser value please use floor(floatvalue)
You can round off decimal values by using NSNumberFormatter
There are some examples you can go through:
NSNumberFormatter *format = [[NSNumberFormatter alloc] init];
[format setPositiveFormat:#"0.##"];
NSLog(#"%#", [format stringFromNumber:[NSNumber numberWithFloat:25.342]]);
NSLog(#"%#", [format stringFromNumber:[NSNumber numberWithFloat:25.3]]);
NSLog(#"%#", [format stringFromNumber:[NSNumber numberWithFloat:25.0]]);
Corresponding results:
2010-08-22 15:04:10.614 a.out[6954:903] 25.34
2010-08-22 15:04:10.616 a.out[6954:903] 25.3
2010-08-22 15:04:10.617 a.out[6954:903] 25
NSString* str = #"2.61111111";
double value = [str doubleValue];
2.5 -> 3: int num = value+0.5;
2.6 -> 3: int num = value+0.4;
Set as your need:
double factor = 0.4
if (value < 0) value *= -1;
int num = value+factor;
NSLog(#"%d",num);

NSDate and AVPlayerItem.currentTime

i know there are a lot of topics, but i canĀ“t find a solution for my problem.
i have an AVPlayerItem and i want the currentTime-property (CMTime) convert to a readable format for my music player.
this is my code:
NSDate *seconds = [[NSDate alloc] initWithTimeIntervalSinceNow:CMTimeGetSeconds(self.playerItem.currentTime)];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:#"HH:mm:ss"];
self.currentTimeLabel.text = [NSString stringWithFormat:#"%#", [timeFormatter stringFromDate:seconds]];
it works but it adds 1 hour to the played Time. how can i subtract that hour?
thx!
try this code,
swift code:
delclare
var playerVal = AVPlayer()
then call below method where you want,
func updateTime() {
let currentTime = Float(CMTimeGetSeconds(playerVal.currentTime()))
let minutes = currentTime/60
let seconds = currentTime - minutes * 60
startValue.text = NSString(format: "%.2f:%.2f", minutes,seconds) as String
}
objective-C code:
delclare
AVPlayer playerVal;
then call below method where you want,
- (void)updateTime {
Float currentTime = CMTimeGetSeconds([playerVal currentTime]);
Float minutes = currentTime/60;
Float seconds = (currentTime - minutes) * 60;
startValue.text = [NSString stringWithFormat:#"%.2f:%.2f", minutes,seconds];
}
its working for me, hope its helpful
thx, i refined it a bit:
float currentTime = CMTimeGetSeconds([self.audioStreamPlayer currentTime]);
int seconds = (int) currentTime;
int minutes = (int) currentTime/60;
int hours = (int) ((currentTime/60)/60);
NSString *hoursString = [NSString stringWithFormat:#"%d",hours];
NSString *minutesString = [NSString stringWithFormat:#"%d",minutes];
NSString *secondsString = [NSString stringWithFormat:#"%d",seconds % 60];
if (hoursString.length == 1) {
hoursString = [NSString stringWithFormat:#"0%d", hours];
}
if (minutesString.length == 1) {
minutesString = [NSString stringWithFormat:#"0%d",minutes];
}
if (secondsString.length == 1) {
secondsString = [NSString stringWithFormat:#"0%d", seconds % 60];
}
self.currentTimeLabel.text = [NSString stringWithFormat:#"%#:%#:%#", hoursString, minutesString, secondsString];
works!

how to seperate '72250' in 72 hr and 250 min in objective c?

Actually I got time interval as 750, so I want split-up in hours and minutes. I was trying but still unable to get. I did following code.
NSTimeInterval interval = 750;
NSDateComponentsFormatter *componentFormatter = [[NSDateComponentsFormatter alloc] init];
componentFormatter.unitsStyle = NSDateComponentsFormatterUnitsStylePositional;
componentFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorDropAll;
NSString *formattedString = [componentFormatter stringFromTimeInterval:interval];
NSLog(#"%#",formattedString);
I think this will help you
- (NSString *)timeInteralToString:(NSTimeInterval)interval {
NSInteger ti = (NSInteger)interval;
NSInteger seconds = ti % 60;
NSInteger minutes = (ti / 60) % 60;
NSInteger hours = (ti / 3600);
return [NSString stringWithFormat:#"%02ld:%02ld", (long)hours, (long)minutes];
}
This Works Correctly:
NSString *value1 = #"7570"; //This is Value
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.usesGroupingSeparator = YES;
[numberFormatter setLocale:[NSLocale localeWithLocaleIdentifier:#" "]];
NSString *formatted = [NSString stringWithFormat: #"%#", [value1 substringWithRange:NSMakeRange(0,2)] ];
NSString *str=[formatted stringByAppendingString:#"hr"];
NSString *formatted2 = [NSString stringWithFormat: #"%#", [value1 substringWithRange:NSMakeRange(2,2)]];
NSString *str2=[formatted2 stringByAppendingString:#"mm"];
NSLog(#"%#",[str stringByAppendingString:str2]);

Time Format so there's only 4 digits with a ":" in the middle

I want the concatenated NSString I have to be output in the format "00:00", the 0s being the digits in the concatenated string. And if there are not enough characters in the NSString, the other digits are made to be 0.
And if there are more than 4 digits than I want to only have the furthest right digits.
I have done this in Java before, I am assuming it's possible in Objective-C as well.
UIButton *button = sender;
NSString *concatenated = [self.input stringByAppendingString: button.titleLabel.text];
self.input = concatenated;
self.userOutput.text = self.input;
For example, I might get "89" as my concatenated string. I then want, self.input = 00:89.
OR
if I get 89374374 from my concatenated string, I then want self.input = 43:74.
I hope I am being clear
The following method should give the desired output:
- (NSString *)getFormattedTimeStringFromString:(NSString *)string
{
int input = [string intValue];
int mins = input % 100;
input /= 100;
int hours = input % 100;
return [NSString stringWithFormat:#"%02d:%02d", hours, mins];
}
You can use this by calling
self.input = [self getFormattedTimeStringFromString:concatenated];
Like this:
NSDateFormatter * df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm"];
NSString *dateTimeStr = [df stringFromDate:[NSDate date]];
if ([concatenated length] == 2) {
self.input = [NSString stringWithFormat:#"00:%#",concatenated];
}
else
{
NSString *test = [concatenated substringFromIndex:[concatenated length] -4];
self.input = [NSString stringWithFormat:#"%#:%#",[test substringToIndex:2],[test substringFromIndex:[test length]-2]];
}
Please try above code it will fail if [concatenated length] is 3 or 1 , modify it accordingly

Removing unnecessary zeros in a simple calculator app

I made a simple calculator and Everytime I hit calculate it'll give a an answer but gives six unnecessary zeros, my question, how can I remove those zeros?
NSString *firstString = textfieldone.text;
NSString *secondString = textfieldtwo.text;
NSString *LEGAL = #"0123456789";
NSCharacterSet *characterSet = [[NSCharacterSet characterSetWithCharactersInString:LEGAL] invertedSet];
NSString *filteredOne = [[firstString componentsSeparatedByCharactersInSet:characterSet]
componentsJoinedByString:#""];
NSString *filteredTwo = [[secondString componentsSeparatedByCharactersInSet:characterSet]
componentsJoinedByString:#""];
firstString = filteredOne;
secondString = filteredTwo;
//Here we are creating three doubles
double num1;
double num2;
double output;
//Here we are assigning the values
num1 = [firstString doubleValue];
num2 = [secondString doubleValue];
output = num1 + num2;
label.text = [NSString stringWithFormat:#"%f",output];
Example:
15 + 15 = 30.000000
I want to add that none of that is necessary if you use the %g specifier.
If you're displaying this by using a string, check the following approaches.
NSString
NSString * display = [NSString stringWithFormat:#"%f", number];
//This approach will return 30.0000000
NSString * display = [NSString stringWithFormat:#"%.2f", number];
//While this approach will return 30.00
Note: You can specify the number of decimals you want to return by adding a point and a number before the 'f'
-Edited-
In your case use the following approach:
label.text = [NSString stringWithFormat:#"%.0f", output];
//This will display your result with 0 decimal places, thus giving you '30'
Please try this out. This should suit your requirements completely.
NSString * String1 = [NSString stringWithFormat:#"%f",output];
NSArray *arrayString = [String1 componentsSeperatedByString:#"."];
float decimalpart = 0.0f;
if([arrayString count]>1)
{
decimalpart = [[arrayString objectAtIndex:1] floatValue];
}
//This will check if the decimal part is 00 like in case of 30.0000, only in that case it would strip values after decimal point. So output will be 30
if(decimalpart == 0.0f)
{
label.text = [NSString stringWithFormat:#"%.0f", output];
}
else if(decimalpart > 0.0f) //This will check if the decimal part is 00 like in case of 30.123456, only in that case it would shows values upto 2 digits after decimal point. So output will be 30.12
{
label.text = [NSString stringWithFormat:#"%.02f",output];
}
Let me know if you need more help.
Hope this helps you.

Resources