Is there any way of preventing number rounding?

 

I'd like to store values with up to a precison of 4 decimal places.  I've investigated some of the functions available that handle precision but all of them perform rounding. Is there are way of preventing this, or a way of only rounding down?


double numberTest = 1.16906;

void OnStart()
  {
  
   Print("a ",numberTest);                    // Output is 1.16906

   Print("b ",NormalizeDouble(numberTest,4)); // Output is 1.1691
   
   Print("c ",DoubleToStr(numberTest,4));     // Output is 1.1691
   
   Print("d ",DoubleToString(numberTest,4));  // Output is 1.1691
   
  }

// I'd like the numberTest to read 1.1690
 

Old school:

void OnStart()
{
    double numberTest = 1.16906;
        
    double truncated = ((long) (numberTest * 10000) / 10000.);
    PrintFormat("%.4f", truncated);
}
 
Anthony Garot:

Old school:

That worked a treat and I thank you for it.  However, I am sitting here with a very large question mark hanging over my head regarding the calculation (and you're quite probably sitting there grinning knowingly about what I'm about to ask you!): Why is it necessary to multiply by 10,000 only then to divide by it?

 
Wit Tank:

That worked a treat and I thank you for it.  However, I am sitting here with a very large question mark hanging over my head regarding the calculation (and you're quite probably sitting there grinning knowingly about what I'm about to ask you!): Why is it necessary to multiply by 10,000 only then to divide by it?

This brings the decimal point to the place that this will work, then dividing takes it back to the original number

5 digits would be 100000 then / 100000.0 etc

MathsFloor or MathsCeil can also be used with the same trick

 

1) 1.16906 * 10000 = 11690.6

2) (long) ( 11690.6 ) = 11690

3) 11690 / 10000. = 1.1690

There are two things for you to note:

A) Conversion to a long wipes out anything after the decimal.

B) The decimal point on the second 10000. is significant. Dividing a long by a double returns a double.

 
Thanks very much, chaps.  I like to understand not only the code but also the reason behind it - many thanks!
 
Wit Tank:
I like to understand not only the code but also the reason behind it
Good attitude. You are on your way to becoming a solid programmer.
 
Anthony Garot:
Good attitude. You are on your way to becoming a solid programmer.
Added to white list ;-)
Reason: