[][src]Module no_proto::pointer::dec

Represents a fixed point decimal number.

Allows floating point values to be stored without rounding errors, useful for storing financial data.

Do NOT perform calculations with .to_float() method, you'll make using this kind of moot.

NP_Dec values contain two parts: 1. The actual number value (num) 2. The position of the decimal point from the right (exp)

A value of "2039.756" could be stored as NP_Dec {num: 2039756, exp: 3}. It could also be stored as: NP_Dec {num: 203975600, exp: 5}.

The range of possible floating point values depends on the exp value. The num property is an i64 variable so it can safely store 9.22e18 to -9.22e18.

If exp is zero, all values stored are whole numbers.

For every increase in exp by 1, the maximum range of possible values decreases by a power of 10. For example at exp = 1 the range drops to 9.22e17 to -9.22e17. However, each increase in exp provides a decimal point of precision. In another example, at exp = 5 you have 5 decimal points of precision and a max range of 9.22e13 to -9.22e13.

Essentially, increaseing the exp factor decreases the maximum range of possible values that can be stored in exchange for increased decimal precision.

NP_Dec values can safely be multiplied, added, devided, subtracted or compared with eachother. It's a good idea to manually shift the exp values of two NP_Dec to match before performing any operation between them, otherwise the operation might not do what you expect.

When NP_Dec values are pulled out of a buffer, the num property is pulled from the buffer contents and the exp property comes from the schema.

use no_proto::pointer::dec::NP_Dec;
 
// Creating a new NP_Dec for 20.49
let mut dec = NP_Dec::new(2049, 2);
 
// add 2
dec += NP_Dec::new(200, 2);
 
// add 0.03
dec += NP_Dec::new(3, 2);
 
// convert float then use it to minus 5
let mut f: NP_Dec = 5.0_f64.into();
f.shift_exp(2); // set new NP_Dec to `exp` of 2.
dec -= f; // subtract
 
assert_eq!(dec.to_float(), 17.52_f64);
 
use no_proto::error::NP_Error;
use no_proto::NP_Factory;
use no_proto::pointer::dec::NP_Dec;
 
let factory: NP_Factory = NP_Factory::new(r#"{
   "type": "dec",
   "exp": 2
}"#)?;

let mut new_buffer = factory.empty_buffer(None, None);
new_buffer.set(&[], NP_Dec::new(50283, 2))?;
 
assert_eq!(502.83f64, new_buffer.get::<NP_Dec>(&[])?.unwrap().to_float());

Structs

NP_Dec

Holds fixed decimal data.