Function ตรวจสอบว่าภายใน Text นั้นมีเฉพาะตัวเลขอย่างเดียวหรือไม่

Spread the love

สวัสดีครับทุกคน วันนี้ผมจะมาแชร์ function สำหรับตรวจสอบว่า ภายในตัวแปร Text ของเรานั้น มีตัวเลขอยู่หรือไม่ ซึ่งเป็น function ที่น่าจะได้ใช้บ่อยพอสมควรระหว่าง coding ภายในโปรแกรม Microsoft Dynamics NAV/365 Business Central อย่างแน่นอน

โดยภายใน function นี้จะประกอบไปด้วย parameter หนึ่งตัว และ return ค่ากลับมาเป็น boolean ครับ

เริ่มต้นประกาศตัวแปร

Text Constant   ENU Value
Text000 100,000.00
Text001 It is a number form.
Text002 It isn’t a number form.

ส่วน code ก็ตามด้านล่างนี้เลยครับ

if IsNumeric(Text000) then
  message(Text001)
else
  message(Text002);

จากคำสั่งด้านบนจะได้ message แสดงออกมาว่า It is a number form.

โอเค งั้นไปดู code ของ function ในการตรวจสอบว่า Text นี้ประกอบด้วยเพียงตัวเลขอย่างเดียวหรือไม่กันเลย

procedure IsNumeric(Text: Text): Boolean;
var
  i: Integer;
begin
  for i := 1 to strlen(Text) do
    if (format(Text[i]) in ['0'..'9']) or (format(Text[i]) in ['.']) then
      if strlen(delchr(Text, '=', delchr(Text,'=', '.'))) <= 1 then
        exit(true)
      else
         exit(false)
    else
      exit(false);
end;

Parameter

Type: Text

ตัวแปร Text ที่คุณต้องการตรวจสอบว่ามีเฉพาะตัวเลขเพียงอย่างเดียวหรือไม่

Return Value

Type: Boolean

ผลลัพธ์ที่ได้กลับมาจาก function เป็น true หรือ false

Remark

ฟังก์ชั่น IsNumber นี้สามารถตรวจจับ comma(,) และ dot (.) ภายใน Text ได้โดยไม่จำเป็นต้องผ่าน function เพื่อลบ characters ก่อนที่จะส่งตัวแปรเข้าไปที่ function

Leave a Reply

Your email address will not be published. Required fields are marked *