Sunday, January 3, 2010

Tip: How to replace a fraction digit with a 0 mathematically?

Sometimes for certain reason, we need to replace certain digit in a value with some fix value. Recently i came across this problem to replace the 3rd digit of a fraction of a number with a 0. I can definitely do it with some string manipulation functions such as substring, replace, etc, but it wont be efficient and string manipulation is a costly process when ran in a loop. I need to figure out a way to do it mathematically using a ligther foot print than the string.

Scenario:
to convert a number 1.567 to 1.560
so basically it's to replace the last digit in the fraction with a 0.
Solution:
1. moves the decimal point by multiplying 100 to the value.
double val = 1.567 * 100 [becomes 156.7]
2. get the whole part of the value by truncating it
double w = Math.Truncate(val); [becomes 156.0]
3. minus off the val with the truncated value w.
double left = val - w; [becomes 0.7]
4. move the left value by dividing it with 100
left = left / 100; [becomes 0.007]
5. deduct the orignal value with the left
double answer = 1.567 - left; [becomes 1.560]