Sunday, February 1, 2009

Convert integer to thai currency

แปลงตัวเลขเป็นหน่วยเงินของไทยเรา

# โค้ด Java อันนี้ดัดแปลงจาก Code PHP

# ขี้เกียจคิดเองอ่ะนะ เลยเอาโค้ดชาวบ้านเค้ามาแก้ ^^'

class HelloWorld
{

public static void main(String[] args)
{
System.out.println(HelloWorld.ToWord("03.22"));

}

public static String ToWord(String inputInt)
{
String value = "";

String []txtnum1 = new String[]{"ศูนย์","หนึ่ง","สอง","สาม","สี่","ห้า","หก","เจ็ด","แปด","เก้า","สิบ"};
String []txtnum2 = new String[]{"","สิบ","ร้อย","พัน","หมื่น","แสน","ล้าน"};

inputInt = inputInt.replaceAll(",","");
inputInt = inputInt.replaceAll(" ","");
inputInt = inputInt.replaceAll("บาท","");

String []nums = inputInt.split("\\.");

if (nums.length > 2)
{
return "Decimal error.";
}

int len = nums[0].length();
String convert = "";

for (int i = 0; i < len; i++)
{

int n = n = Integer.parseInt(nums[0].substring(i, i+1));

if (n != 0)
{
if (i == (len - 1) && n == 1)
{
convert += "เอ็ด";
}
else if (i == (len - 2) && n == 2)
{
convert += "ยี่";
}
else if (i == (len - 2) && n == 1)
{
convert += "";
}
else
{
convert += txtnum1[n];
}

convert += txtnum2[len - i - 1];
}
}

convert += "บาท";

if (nums[1].length() > 2)
{
nums[1] = nums[1].substring(0, 2);
}


if (nums[1] == "0" || nums[1] == "00" || nums[1] == "")
{
convert += "ถ้วน";
}
else
{
len = nums[1].length();

for (int i = 0; i < len; i++)
{
int n = Integer.parseInt(nums[1].substring(i, i+1));

if (n != 0)
{
if (i == (len - 1) && n == 1)
{
convert += "เอ็ด";
}
else if (i == (len - 2) && n == 2)
{
convert += "ยี่";
}
else if (i == (len - 2) && n == 1)
{
convert += "";
}
else
{
convert += txtnum1[n];
}

convert += txtnum2[len - i - 1];
}
}

convert += "สตางค์";
}

value = convert;

return value;
}
}




Related Posts:
References:

No comments:

Post a Comment