Tema: Redondeo
Ver Mensaje Individual
  #29  
Antiguo 22-04-2014
Avatar de nlsgarcia
[nlsgarcia] nlsgarcia is offline
Miembro Premium
 
Registrado: feb 2007
Ubicación: Caracas, Venezuela
Posts: 2.206
Reputación: 21
nlsgarcia Tiene un aura espectacularnlsgarcia Tiene un aura espectacular
novato_erick,

Cita:
Empezado por novato_erick
...Alguna mejor idea de funciones de redondeo que me retorne valores deseados reales...21,465 debería darme 21,47...
Revisa este código:
Código Delphi [-]
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Math;

type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    ListBox2: TListBox;
    Button1: TButton;
    Label1: TLabel;
    Label2: TLabel;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function RoundNumber(Number: Double; Decimal: Integer): Double;

   function DoubleDecimals(Number : Double; Decimal : Integer) : Double;
   var
      AuxNumber : String;
   begin

      AuxNumber := FloatToStr(Number);

      if Pos('.',AuxNumber) > 0 then
         Result := StrToFloat(Copy(AuxNumber,1,Pos('.',AuxNumber) + Decimal))
      else
      if Pos(',',AuxNumber) > 0 then
         Result := StrToFloat(Copy(AuxNumber,1,Pos(',',AuxNumber) + Decimal))
      else
         Result := Number;
   end;

var
   Factor: Double;

begin

   Factor := IntPower(10,Decimal);

   if Number > 0 then
      Result := DoubleDecimals((Number * Factor + 0.5) / Factor,Decimal)
   else
      Result := DoubleDecimals((Number * Factor - 0.5) / Factor,Decimal);

end;

procedure TForm1.FormCreate(Sender: TObject);
begin

   ListBox1.Items.Add('21,464');
   ListBox1.Items.Add('-21,464');
   ListBox1.Items.Add('21,465');
   ListBox1.Items.Add('-21,465');
   ListBox1.Items.Add('21,466');
   ListBox1.Items.Add('-21,466');
   ListBox1.Items.Add('3,1415927');
   ListBox1.Items.Add('-3,1415927');
   ListBox1.Items.Add('2,718281');
   ListBox1.Items.Add('-2,718281');
   ListBox1.Items.Add('5,264');
   ListBox1.Items.Add('-5,264');
   ListBox1.Items.Add('5,265');
   ListBox1.Items.Add('-5,265');
   ListBox1.Items.Add('5,267');
   ListBox1.Items.Add('-5,267');

end;

procedure TForm1.Button1Click(Sender: TObject);
var
   i : Integer;
   N1 : Double;

begin

   DecimalSeparator := ',';
   ThousandSeparator := '.';

   for i := 0 to ListBox1.Items.Count - 1 do
   begin
      N1 := StrToFloat(ListBox1.Items.Strings[i]);
      ListBox2.Items.Add(FloatToStr(RoundNumber(N1,2)));
   end;

end;

end.
El código anterior redondea un número tipo double al número de decimales especificados con redondeo al infinito, como se muestra en la siguiente imagen:



Espero sea útil

Nelson.

Última edición por nlsgarcia fecha: 22-04-2014 a las 21:30:27.
Responder Con Cita