objective c - iOS Float/Double without rounding -


ok had pretty dumb question. need separate float two:

  • first part contain whole number part , 2 digits after decimal dot
  • second item should contain third , fourth digits float

the important thing not want rounding(whether or down). pretty following:

12.8 => 12.80 && 00 12.8999999999 => 12.89 && 99 12.899999 => 12.89 && 99 12.0005 => 12.00 && 05 

the format string approach

i need 4 digits after decimal point no matter what, need use %.4f or %f(and cut last 2 components) in order handle 12.8 => 12.8000. when number has many 9's after decimal point auto-round-up present:

let test = 122.899999999999 let sut = string(format: "%f", test) // 122.900000 instead of 122.899999 

round approach

i tried use standard c floor method should round down float. if 9's after decimal point way greater "divider" floor acts round:

let test = 122.89999999999999  let divider = 10000.0  let sut = (double(floor(test * divider)) / divider) // 122.9 instead of 122.8999 

so advices welcomed :)

don't use float, float not precise. use nsdecimalnumber. nsdecimalnumber class provides fixed-point arithmetic capabilities. they’re designed perform base-10 calculations without loss of precision , predictable rounding behavior. makes better choice representing currency floating-point data types double. however, trade-off more complicated work with.

nsdecimalnumber *price1 = [[nsdecimalnumber alloc] initwithfloat:15.99f]] ; nsdecimalnumber *price1 = [[nsdecimalnumber alloc] initwithfloat:29.99f]] ; nslog(@"subtotal: %@", [price1 decimalnumberbyadding:price2]);  

it output 45.98.

see this.

edit:

here apples documentation nsdecimalnumber.


Comments