Creating a two decimal number from a float - not for display
I having been using floating number types in some calculations. I use NSLog to view the values in the console and they are appearing in scientific notation. I want the values to be represented by two decimal places for the calculations...not开发者_开发百科 the display. How do I conver to two decimals?
If you're attempting to perform fixed-point arithmetic, then use int
or long int
data types to represent hundredths, and when you want to display the values, divide by 100.0f
. Also look at using NSNumberFormatter
.
I don't know the language, but one can usually do this using something like
int(n * 100 + 0.5) / 100
Be sure to check the available libraries for a function named round
or similar. In Perl, I would just use
sprintf("%.2f", $n)
This does rounding and the result can be used as a number.
精彩评论