您的位置:首页 > 编程语言 > C#

大写金额字符串生成 C#实现

2014-03-29 22:00 267 查看
思路:
  中文对金额的描述以四位为一组,
  只考虑一万亿以内的数字则每组内以千、百、十和[亿\万\元]区分各位
  连续的零按一个处理,组内最低位的零可略去
  无角无分说整,有角无分只说角,无角有分说零X分,有角有分...

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MorrisSpace
{
/// <summary>
/// 中文金额字符串辅助类。Helper for Amount string in Chinese
/// </summary>
public class AmountStringHelper
{
static private readonly char[] units = { '分', '角', '拾', '佰', '仟', '圆', '万', '亿', '整' };
//                                        0     1     2     3     4     5     6     7    8
static private readonly char[] numbers = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' };

/// <summary>
/// 数字金额转大写金额
/// </summary>
/// <param name="num">金额数字</param>
/// <returns>大写金额字符串</returns>
public static string GetAmountInWords(double num)
{
double amount = Math.Round(num, 2);
long integ = (int)amount;
double fract = Math.Round(amount - integ, 2);
if (integ.ToString().Length > 12)
{
return null;
}
string result = "";
if (fract - 0.0 != 0)
{
string tempstr = fract.ToString();
if (tempstr.Length == 3)
{
result += numbers[(int)(fract * 10)];
result += units[1];
}
else
{
int frist = (int)(fract * 10);
int second = (int)(fract * 100 - frist * 10);
if (frist != 0)
{
result += numbers[frist];
result += units[1];
result += numbers[second];
result += units[0];
}
else
{
result += numbers[0];
result += numbers[second];
result += units[0];
}
}
}
else
{
result += units[8];
}

for (int temp = (int)(integ % 10000), secnum = 1; temp != 0; temp = (int)(integ % 10000), secnum++)
{
result = FourBitTrans(temp) + units[secnum + 4] + result;
integ /= 10000;
if (integ != 0 && temp < 1000)
{
result = numbers[0] + result;
}
}
return result;
}

/// <summary>
/// 进行四位数字转换的辅助函数
/// </summary>
/// <param name="num">四位以下数字</param>
/// <returns>大写金额四位节</returns>
public static string FourBitTrans(int num)
{
string tempstr = num.ToString();
if (tempstr.Length > 4)
{
return null;
}
string result = string.Empty;
int i = tempstr.Length;
int j = 0;
bool zeromark = true;
while (--i >= 0)
{
j++;

if (tempstr[i] == '0')
{
if (zeromark == true)
{
continue;
}
zeromark = true;
result = numbers[0] + result;
continue;
}
zeromark = false;
if (j > 1)
{
result = units[j] + result;
}
int temp = tempstr[i] - '0';
result = numbers[temp] + result;
}
return result;
}

}
}


--------------------------------------

这个代码只适合一亿以内的金额,但相信以满足绝大多数情况
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: