Stripping extra decimal spaces
BlitzMax Forums/BlitzMax Beginners Area/Stripping extra decimal spaces
| ||
| Hi all I made a simple salary calculator as a test to learn a bit of MaxGUI. This is a pretty basic question but I can't find an answer in the docs. How do I round a Long number to, say, two decimal places. The thing is, when I do my calculation, the result comes out like this: 206.0000000000000 Any info will be greatly appreciated! |
| ||
| You can convert it to a string, and then remove all characters that occur N characters after the "." |
| ||
Function RoundedToDecimalPlaces:String(number:Double, places:Int)
Local numberString:String = String(number)
Return numberString[0..numberString.Find(".")+places+1]
End Function
|
| ||
| Assuming it has "." in there, otherwise it's going to return something entirely unexpected. |
| ||
| Assuming it has "." in there, otherwise it's going to return something entirely unexpected A double will always have a decimal point in it, won't it? |
| ||
| At least on Mac and Windows, using the current BMX, BlitzMax's String representation of a Double always contains a '.' as far as I can tell. I couldn't find a counterexample, anyway. It is the sort of thing that could get changed between updates, though. |
| ||
| A double will always have a decimal point in it, won't it? Let's hope so. |
| ||
| you can end up with a scientific notation valid on intel and ppc computers. try this: a! = 20.0!/21808999899! Print a! |
| ||
| Oh yeah.... you could parse the string to allow for that though. |
| ||
| I would like to see a salary involving scientific notation. :) That having been said, I definitely stand corrected. THAT having been said, when dealing with monetary values, it's best to avoid the whole floating-point thing anyway -- you might want to consider either using arbitrary-precision arithmetic or storing monetary values as a number of cents (ie, $7.82 as 782) in order to avoid this sort of problem. |
| ||
Something like this?Function decround$(n!,k:Int) Local i:Int i=Int(n) If Floor(n)=n Or k=0 Return String(i) n:-i n:*10^k Local d:Int=Int(n) If n-d>.5 Then d:+1 Return String(i)+"."+String(d) End Function For k=0 To 5 Print decround(Pi,k) Next |
| ||
| Though yes, for salaries store money as numbers of pennies and use bankers' rounding |