How to trim zeros after decimal point

后端 未结 8 1672
栀梦
栀梦 2021-01-05 05:38

I am trying to trim zeros after a decimal point as below but it\'s not giving desired result.

trig = [currentVal doubleValue];
trig = trig/100;
NSNumberForma         


        
8条回答
  •  情话喂你
    2021-01-05 06:13

    In case this helps someone. I wanted 1 decimal value but no '.0' on the end if the float was '1.0'. Using %g would give scientific notation for longer numbers, following ugliness worked well enough for me as high accuracy wasn't critical.

    // Convert to 1 dp string,
    NSString* dirtyString = [NSString stringWithFormat: @"%.1f", self.myFloat];
    
    // Convert back to float that is now a maximum of 1 dp,
    float myDirtyFloat = [dirtyString floatValue];
    
    // Output the float subtracting the zeros the previous step attached
    return [NSString stringWithFormat: @"%g", myDirtyFloat];
    

提交回复
热议问题