I did a bit of currency processing testing, for example. Go and Dart. Basically, I think the best way to handle currencies is to convert double numbers to integers so that all calculations are done using integers, and I think this is an acceptable way. However, different languages ββview conversion to whole differently. For example, Go truncates doubles, so I find it necessary to add a rounding factor to compensate. Using Rust, I found that performing a direct transform (see below) works, but I'm not sure if Rust actually handles the transform using what appears to be two alternatives for processing the transform.
How does Rust handle rounding f64 to i64 and what is the best method to use "like i64" or "to_i64 ()"?
Based on the timings I made, the two methods here do not look the same, however there may be results. ("like i64" appeared a little faster).
Example (simplified to use only 2 decimal places - single currency):
fn fCcyDblToInt(dCcyAmt: f64) -> i64 { // return (dCcyAmt * 100.0).to_i64(); return (dCcyAmt * 100.0) as i64; }
Edited 14 hours after the first post:
After doing a few more tests, it seems to me a way to handle the conversion of a float to integer using Rust:
fn fCcyDblToInt(dCcyAmt:f64) -> i64 { let dRound: f64 = if dCcyAmt > 0.0 { 0.5 } else if dCcyAmt < 0.0 {-0.5 } else {0.0}; // return ((dCcyAmt * 100.0) +dRound).to_i64(); return ((dCcyAmt * 100.0) +dRound) as i64; }
Itβs quite convenient for me, because this is how I dealt with it elsewhere, however I will spend a little more.
rust
Brian oh
source share