2
0

Quick.Format.pas 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. { ***************************************************************************
  2. Copyright (c) 2016-2018 Kike Pérez
  3. Unit : Quick.Format
  4. Description : String Format functions
  5. Author : Kike Pérez
  6. Version : 1.4
  7. Created : 14/07/2017
  8. Modified : 19/07/2018
  9. This file is part of QuickLib: https://github.com/exilon/QuickLib
  10. ***************************************************************************
  11. Licensed under the Apache License, Version 2.0 (the "License");
  12. you may not use this file except in compliance with the License.
  13. You may obtain a copy of the License at
  14. http://www.apache.org/licenses/LICENSE-2.0
  15. Unless required by applicable law or agreed to in writing, software
  16. distributed under the License is distributed on an "AS IS" BASIS,
  17. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. See the License for the specific language governing permissions and
  19. limitations under the License.
  20. *************************************************************************** }
  21. unit Quick.Format;
  22. {$i QuickLib.inc}
  23. interface
  24. uses
  25. SysUtils,
  26. Math;
  27. //converts a number to thousand delimeter string
  28. function NumberToStr(const Number : Int64) : string;
  29. //convert bytes to KB, MB, TB...
  30. function FormatBytes(const aBytes : Int64; Spaced : Boolean = False) : string;
  31. implementation
  32. function NumberToStr(const Number : Int64) : string;
  33. begin
  34. try
  35. Result := FormatFloat('0,',Number);
  36. except
  37. Result := '#Error';
  38. end;
  39. end;
  40. function FormatBytes(const aBytes : Int64; Spaced : Boolean = False) : string;
  41. const
  42. mesure : array [0..8] of string = ('Byte(s)', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
  43. var
  44. i : Integer;
  45. bfmt : string;
  46. cspace : Char;
  47. begin
  48. i := 0;
  49. while aBytes > Power(1024, i + 1) do Inc(i);
  50. if Spaced then cspace := Char(32)
  51. else cspace := Char(0);
  52. // bfmt := '%.2f %s'
  53. //else bfmt := '%.2f%s';
  54. if i < 2 then bfmt := '%.0f%s%s'
  55. else bfmt := '%.2f%s%s';
  56. Result := Format(bfmt,[aBytes / IntPower(1024, i),cspace,mesure[i]]);
  57. end;
  58. end.