How to trim zeros after decimal point

后端 未结 8 1667
栀梦
栀梦 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:17

    This will not display any decimal value after the decimal point:

    display.text = [NSString stringWithFormat:@"%1.0f", trig];
    

    This will just trim the zeros after the decimal point:

    isplay.text = [NSString stringWithFormat:@"%3.2f", trig];
    display.text = [display.text stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:[NSString stringWithFormat@"0"]]];
    

    Note, this may leave you with the trailing decimal point. "124." may happen. I guess that some smarter solution will be posted soon.

    0 讨论(0)
  • 2021-01-05 06:19

    Sometimes the straight C format specifiers do an easier job than the Cocoa formatter classes, and they can be used in the format string for the normal stringWithFormat: message to NSString.

    If your requirement is to not show any trailing zeroes, then the "g" format specifier does the job:

    float y = 1234.56789f;
    
    NSString *s = [NSString stringWithFormat:@"%g", y];
    

    Notice that there is no precision information, which means that the printf library will remove the trailing zeroes itself.

    There is more information in the docs, which refer to IEEE's docs.

    0 讨论(0)
提交回复
热议问题