code_junkie

Use Float or Decimal for Accounting Application Dollar Amount?

Nov 10th, 2011
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. 1/4 1/8 1/16 1/32
  2.  
  3. int cents = num % 100;
  4. int dollars = (num - cents) / 100;
  5. printf("%d.%02d", dollars, cents);
  6.  
  7. #include <stdio.h>
  8.  
  9. int main()
  10. {
  11. printf("Mapping 100 numbers between 0 and 1 ");
  12. printf("to their hexadecimal exponential form (HEF).n");
  13. printf("Most of them do not equal their HEFs. That means ");
  14. printf("that their representations as floats ");
  15. printf("differ from their actual values.n");
  16. double f = 0.01;
  17. int i;
  18. for (i = 0; i < 100; i++) {
  19. printf("%1.2f -> %an",f*i,f*i);
  20. }
  21. printf("Printing 128 'float-compatible' numbers ");
  22. printf("together with their HEFs for comparison.n");
  23. f = 0x1p-7; // ==0.0071825
  24. for (i = 0; i < 0x80; i++) {
  25. printf("%1.7f -> %an",f*i,f*i);
  26. }
  27. return 0;
  28. }
  29.  
  30. DECLARE @Float1 float, @Float2 float, @Float3 float, @Float4 float;
  31. SET @Float1 = 54;
  32. SET @Float2 = 3.1;
  33. SET @Float3 = 0 + @Float1 + @Float2;
  34. SELECT @Float3 - @Float1 - @Float2 AS "Should be 0";
  35.  
  36. Should be 0
  37. ----------------------
  38. 1.13797860024079E-15
  39.  
  40. DECLARE @Fixed1 decimal(8,4), @Fixed2 decimal(8,4), @Fixed3 decimal(8,4);
  41. SET @Fixed1 = 54;
  42. SET @Fixed2 = 0.03;
  43. SET @Fixed3 = 1 * @Fixed1 / @Fixed2;
  44. SELECT @Fixed3 / @Fixed1 * @Fixed2 AS "Should be 1";
  45.  
  46. Should be 1
  47. ---------------------------------------
  48. 0.99999999999999900
Add Comment
Please, Sign In to add comment