C#实现数字转换汉字的示例详解

目录
  • 实践过程
    • 效果
    • 代码

实践过程

效果

代码

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    public static string CNumToCh(string x)
    {
        //数字转换为中文后的数组
        string[] num = new string[] { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
        //为数字位数建立一个位数组
        string[] digit = new string[] { "", "拾", "佰", "仟" };
        //为数字单位建立一个单位数组
        string[] units = new string[] { "", ",万,", ",亿,", ",万亿," };
        string returnValue = ""; //返回值
        int finger = 0; //字符位置指针
        int m = x.Length % 4; //取模
        int k = 0;
        if (m > 0)
            k=x.Length / 4 + 1;
        else
            k=x.Length / 4;
        //外层循环,四位一组,每组最后加上单位: ",万亿,",",亿,",",万,"
        for (int i = k; i > 0; i--)
        {
            int L = 4;
            if (i == k && m != 0)
                L = m;
            //得到一组四位数
            string four = x.Substring(finger, L);
            int l = four.Length;
            //内层循环在该组中的每一位数上循环
            for (int j = 0; j < l; j++)
            {
                //处理组中的每一位数加上所在的位
                int n = Convert.ToInt32(four.Substring(j, 1));
                if (n == 0)
                {
                    if (j < l - 1&& Convert.ToInt32(four.Substring(j + 1, 1)) > 0 && !returnValue.EndsWith(num[n]))
                        returnValue += num[n];
                }
                else
                {
                    if (!(n == 1 && (returnValue.EndsWith(num[0]) | returnValue.Length == 0) && j == l - 2))
                        returnValue += num[n];
                    returnValue += digit[l - j - 1];
                }
            }
            finger += L;
            //每组最后加上一个单位:",万,",",亿," 等
            if (i < k) //如果不是最高位的一组
            {
                if (Convert.ToInt32(four) != 0)
                    //如果所有4位不全是0则加上单位",万,",",亿,"等
                    returnValue += units[i - 1];
            }
            else
            {
                //处理最高位的一组,最后必须加上单位
                returnValue += units[i - 1];
            }
        }
        return returnValue;
    } 

    private void button1_Click(object sender, EventArgs e)
    {
        if (txtStr.Text.Trim() == "")
        {
            return;
        }
        else
        {
            if (txtStr.Text.Trim().Length > 16)
            {
                MessageBox.Show("数字金额太大!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                if (txtStr.Text.Trim().Substring(0, 1) == "0")
                {
                    MessageBox.Show("请正确输入金额!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    richTextBox1.Text = CNumToCh(txtStr.Text.Trim());
                }
            }
        }
    }

    private void txtStr_KeyPress(object sender, KeyPressEventArgs e)
    {
        if((e.KeyChar!=8&&!char.IsDigit(e.KeyChar))&&e.KeyChar!=13)
        {
            MessageBox.Show("请输入数字!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            txtStr.Text = "";
            txtStr.Focus();
        }
    }
}
partial class Form1
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.label2 = new System.Windows.Forms.Label();
        this.label1 = new System.Windows.Forms.Label();
        this.button1 = new System.Windows.Forms.Button();
        this.richTextBox1 = new System.Windows.Forms.RichTextBox();
        this.txtStr = new System.Windows.Forms.TextBox();
        this.SuspendLayout();
        //
        // label2
        //
        this.label2.AutoSize = true;
        this.label2.Location = new System.Drawing.Point(17, 53);
        this.label2.Name = "label2";
        this.label2.Size = new System.Drawing.Size(65, 12);
        this.label2.TabIndex = 8;
        this.label2.Text = "转换结果:";
        //
        // label1
        //
        this.label1.AutoSize = true;
        this.label1.Location = new System.Drawing.Point(17, 15);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(65, 12);
        this.label1.TabIndex = 7;
        this.label1.Text = "输入数字:";
        //
        // button1
        //
        this.button1.Location = new System.Drawing.Point(329, 11);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(75, 23);
        this.button1.TabIndex = 5;
        this.button1.Text = "开始转换";
        this.button1.UseVisualStyleBackColor = true;
        this.button1.Click += new System.EventHandler(this.button1_Click);
        //
        // richTextBox1
        //
        this.richTextBox1.Location = new System.Drawing.Point(79, 53);
        this.richTextBox1.Name = "richTextBox1";
        this.richTextBox1.Size = new System.Drawing.Size(325, 131);
        this.richTextBox1.TabIndex = 9;
        this.richTextBox1.Text = "";
        //
        // txtStr
        //
        this.txtStr.Location = new System.Drawing.Point(79, 12);
        this.txtStr.Name = "txtStr";
        this.txtStr.Size = new System.Drawing.Size(244, 21);
        this.txtStr.TabIndex = 6;
        this.txtStr.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtStr_KeyPress);
        //
        // Form1
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(414, 196);
        this.Controls.Add(this.richTextBox1);
        this.Controls.Add(this.txtStr);
        this.Controls.Add(this.label2);
        this.Controls.Add(this.label1);
        this.Controls.Add(this.button1);
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
        this.MaximizeBox = false;
        this.MinimizeBox = false;
        this.Name = "Form1";
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.Text = "数字大小写转换";
        this.ResumeLayout(false);
        this.PerformLayout();

    }

    #endregion

    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.RichTextBox richTextBox1;
    private System.Windows.Forms.TextBox txtStr;
}

到此这篇关于C#实现数字转换汉字的示例详解的文章就介绍到这了,更多相关C#数字转汉字内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C#把数字转换成大写金额的代码实例

    实现代码: 复制代码 代码如下: // 例如:(new Money(200)).ToString() == "贰佰元"namespace Skyiv.Util {    using System.Text;    class Test {        static void Main() {            for (;;) {                System.Console.Write("金额: ");                strin

  • C#算法之罗马数字转整数

    罗马数字转整数 罗马数字包含以下七种字符: I, V, X, L,C,D 和 M. 字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000 例如, 罗马数字 2 写做 II ,即为两个并列的 1.12 写做 XII ,即为 X + II . 27 写做  XXVII, 即为 XX + V + II . 通常情况下,罗马数字中小的数字在大的数字的右边.但也存在特例,例如 4 不写做 IIII,而是 IV.数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1

  • C#实现数字转换

    本文实例为大家分享了C#实现数字转换的具体代码,供大家参考,具体内容如下 1 题目描述:数字转换 从键盘接收一个字符串,将其转换成一个double类型的数据,若转换成功,则显示转换之后的结果(保留小数点之后的4位,小数点之前的数字每3位加一个逗号):若转换失败,则显示提示信息,并继续接收用户输入,重新转换: 2 源码详解 using System; namespace Csharp6_2 { class Program { static void Main(string[] args) { wh

  • C#基于纯数学方法递归实现货币数字转换中文功能详解

    本文实例讲述了C#基于纯数学方法递归实现货币数字转换中文功能.分享给大家供大家参考,具体如下: 最近由于项目的原因,需要写一个货币数字转换中文的算法,先在网了找了一下,结果发现无一列外都是用(Replace)替换的方式来实现的,所以想写个另外的算法:因为本人是学数学出身的,所以用纯数学的方法实现. 注意:本文中的算法支持小于1023 (也就是9999亿兆)货币数字转化. 货币中文说明: 在说明代码之前,首先让我们回顾一下货币的读法. 10020002.23  读为 壹仟零贰万零贰元贰角叁分 10

  • C#将数字转换成字节数组的方法

    本文实例讲述了C#将数字转换成字节数组的方法.分享给大家供大家参考.具体实现方法如下: 下面的代码用到了MemoryStream 和 BinaryWriter // Create a byte array from a decimal public static byte[] DecimalToByteArray (decimal src) { // Create a MemoryStream as a buffer to hold the binary data using (MemorySt

  • C#实现数字转换汉字的示例详解

    目录 实践过程 效果 代码 实践过程 效果 代码 public partial class Form1 : Form { public Form1() { InitializeComponent(); } public static string CNumToCh(string x) { //数字转换为中文后的数组 string[] num = new string[] { "零", "壹", "贰", "叁", "

  • Python实现图像尺寸和格式转换处理的示例详解

    实现代码 # batch_handle_image.py import argparse import glob import os from PIL import Image def main(args): limit_shortest = int(args.limitshortest) shortest_edge = int(args.shortestedge) longest_edge = int(args.longestedge) limit_width_or_height = int(

  • java数字转汉字工具类详解

    本文实例为大家分享了java数字转汉字工具类的具体代码,供大家参考,具体内容如下 /** * Created by 33303 on 2017/7/28. */ import java.math.BigDecimal; /** * 数字转换为汉语中人民币的大写<br> * */ public class NumberToCN { /** * 汉语中数字大写 */ private static final String[] CN_UPPER_NUMBER = { "零", &

  • Python实现数字小写转大写的示例详解

    目录 前言 代码实现 测试 补充 前言 这绝对是个非常有趣的问题哈哈,但用python列表实现就变得比较烧脑,正常人不会非常较真这样的程序,我也只是闲来无事,如果代码还是有bug,那么我也没办法. 注:经过广泛搜索和仔细深究,似乎没有几套开源代码能100%满足要求 参考标准:大小写转换器_人民币大写在线转换工具 代码实现 首先将一个数字根据小数点,进行分割.建立字典和数据集(left_chinese, right_chinese),这里left_chinese不加元,是因为后面可以统一处理,避免

  • java时区转换的理解及示例详解

    一.时区的基本概念 GMT(Greenwich Mean Time),即格林威治标准时,是东西经零度的地方.人们将地球人为的分为24等份,每一等份为一个时区,每时区横跨经度15度,时间正好为1小时.往西一个时区,则减去一小时:往东一个时区,则加上一小时.中国在东经120度上,(东经120°-东经0°)所得度数再除以15,即得8. UTC(Coordinated Universal Time),即世界协调时间,是经过平均太阳时(以格林威治时间GMT为准).地轴运动修正后的新时标以及以「秒」为单位的

  • mybatis写xml时数字类型千万别用 !=‘‘(不为空串)进行判断的示例详解

    前言 最近项目内更新数据时,发现数字类型字段设置为0时不能正常的更新进数据库,我们打印了下mybatis的sql日志发现字段为0的sql没有被拼接. 样例 下面的是错误示例 ❌ <update id="update" parameterType="com.chengfengfeng.test.domain.People"> update people set <if test="age!=null and age !=''"&g

  • Go Java算法猜数字游戏示例详解

    目录 猜数字游戏 方法一:遍历(Java) 方法一:遍历(Go) 猜数字游戏 你在和朋友一起玩 猜数字(Bulls and Cows)游戏,该游戏规则如下: 写出一个秘密数字,并请朋友猜这个数字是多少.朋友每猜测一次,你就会给他一个包含下述信息的提示: 猜测数字中有多少位属于数字和确切位置都猜对了(称为 "Bulls",公牛), 有多少位属于数字猜对了但是位置不对(称为 "Cows",奶牛).也就是说,这次猜测中有多少位非公牛数字可以通过重新排列转换成公牛数字. 给

  • Angular.js 实现数字转换汉字实例代码

    AngularJS 简介 AngularJS 是一个 JavaScript 框架.它可通过 <script> 标签添加到 HTML 页面. AngularJS 通过 指令 扩展了 HTML,且通过 表达式 绑定数据到 HTML. 下面通过本文给大家介绍Angular.js 实现数字转换汉字实例代码,具体代码如下所示: // 1.实现输入数字输出对应汉字,要求使用angularjs,不准使用$watch函数,for循环:提示:ng-change指令 <div ng-app="my

  • JS的时间格式化和时间戳转换函数示例详解

    JS的时间格式化和时间戳转换函数 //格式化时间 function dateFormat(fmt,date){ var o = { "M+" : date.getMonth()+1, //月份 "d+" : date.getDate(), //日 "h+" : date.getHours(), //小时 "m+" : date.getMinutes(), //分 "s+" : date.getSeconds

  • Python线性点运算数字图像处理示例详解

    目录 点运算 定义 分类 线性点运算 分段线性点运算 非线性点运算 对数变换 幂次变换 点运算 定义 分类 线性点运算 例子: 分段线性点运算 非线性点运算 对数变换 幂次变换 1. 点运算是否会改变图像内像素点之间的空间位置关系? 点运算是一种像素的逐点运算,它与相邻的像素之间没有运算关系,点运算不会改变图像内像素点之间的空间位置关系. 2. 对图像灰度的拉伸,非线性拉伸与分段线性拉伸的区别? 非线性拉伸不是通过在不同灰度值区间选择不同的线性方程来实现对不同灰度值区间的扩展与压缩,而是在整个灰

随机推荐