开发者

Creating a two decimal number from a float - not for display

开发者 https://www.devze.com 2023-02-27 05:47 出处:网络
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 de

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消