Note that there are some explanatory texts on larger screens.

plurals
  1. POLoss of precision converting 'float' to NSNumber, back to 'float'
    primarykey
    data
    text
    <p>I seem to be encountering a strange issue in Objective-C converting a float to an NSNumber (wrapping it for convenience) and then converting it back to a float.</p> <p>In a nutshell, a class of mine has a property <code>red</code>, which is a float from <code>0.0</code> to <code>1.0</code>:</p> <pre><code>@property (nonatomic, assign) float red; </code></pre> <p>This object is comparing itself to a value that is loaded from disk, for synchronization purposes. (The file can change outside the application, so it checks periodically for file changes, loads the alternate version into memory, and does a comparison, merging differences.)</p> <p>Here's an interesting snippet where the two values are compared:</p> <pre><code>if (localObject.red != remoteObject.red) { NSLog(@"Local red: %f Remote red: %f", localObject.red, remoteObject.red); } </code></pre> <p>Here's what I see in the logs:</p> <pre><code>2011-10-28 21:07:02.356 MyApp[12826:aa63] Local red: 0.205837 Remote red: 0.205837 </code></pre> <p>Weird. Right? How is this piece of code being executed?</p> <p>The actual value as stored in the file:</p> <pre><code>...red="0.205837"... </code></pre> <p>Is converted to a <code>float</code> using:</p> <pre><code>currentObject.red = [[attributeDict valueForKey:@"red"] floatValue]; </code></pre> <p><strong>At another point in the code</strong> I was able to snag a screenshot from GDB. It was printed to NSLog as: (This is also the precision with which it appears in the file on disk.)</p> <pre><code>2011-10-28 21:21:19.894 MyApp[13214:1c03] Local red: 0.707199 Remote red: 0.707199 </code></pre> <p>But appears in the debugger as:</p> <p><img src="https://i.stack.imgur.com/0i0mX.png" alt="GDB Screenshot"></p> <p>How is this level of precision being obtained at the property level, but not stored in the file, or printed properly in NSLog? <em>And why does it seem to be varying?</em></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload