I have the value 25.00
in a float
, but when I print it on screen it is 25.0000000
.
How can I display the value with only two decimal places?
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- back button text does not change
- iOS (objective-c) compression_decode_buffer() retu
- how to find the index position of the ARRAY Where
相关文章
- 现在使用swift开发ios应用好还是swift?
- How can I convert a f64 to f32 and get the closest
- TCC __TCCAccessRequest_block_invoke
- xcode 4 garbage collection removed?
- Unable to process app at this time due to a genera
- How can I add media attachments to my push notific
- didBeginContact:(SKPhysicsContact *)contact not in
- Custom Marker performance iOS, crash with result “
in objective -c is u want to display float value in 2 decimal number then pass argument indicating how many decimal points u want to display e.g 0.02f will print 25.00 0.002f will print 25.000
You can also try using NSNumberFormatter:
You may need to also set the negative format, but I think it's smart enough to figure it out.
Here's some methods to format dynamically according to a precision:
e.g.
=> 2.3453
=> 2
=> 2.35 (round up)
The problem with all the answers is that multiplying and then dividing results in precision issues because you used division. I learned this long ago from programming on a PDP8. The way to resolve this is:
Thus 15.6578 returns just 15.66 and not 15.6578999 or something unintended like that.
What level of precision you want is up to you. Just don't divide the product, multiply it by the decimal equivalent. No funny String conversion required.
It is not a matter of how the number is stored, it is a matter of how you are displaying it. When converting it to a string you must round to the desired precision, which in your case is two decimal places.
E.g.:
%.02f
tells the formatter that you will be formatting a float (%f
) and, that should be rounded to two places, and should be padded with0
s.E.g.: