Vue字符串里的中文数字转换为阿拉伯数字

22 篇文章 0 订阅
17 篇文章 0 订阅

js字符串里的汉字数字转化为数字

<template>
	<view>
		<view>
			<view class="inpbox" >
				<textarea v-model="voiceMane" @input="convert" ></textarea>
			</view>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				chineseNumberMap: {
					'零': 0,
					'一': 1,
					'二': 2,
					'三': 3,
					'四': 4,
					'五': 5,
					'六': 6,
					'七': 7,
					'八': 8,
					'九': 9,
					'十': 10,
					'百': 100,
					'千': 1000,
					'万': 10000,
					'两': 2,
				},
				voiceMane:''
			};
		},
		methods: {
			convert() {
				this.cs(this.voiceMane);
			},
			cs(str) {
				let _this = this;
				let convertedStr = str.replace(/[一二三四五六七八九十零百千万两]+/g, match => {
					// 对于匹配到的每个汉字数字,调用转换函数进行转换
					return _this.convertChineseToArabic(match).toString();
				});
				let tstring = convertedStr.replace(//g, '.');
				console.log(tstring)  // 输出结果
			},
			convertChineseToArabic(chineseNumber) {
				let result = 0;
				let currentNumber = 0;
				for (let i = 0; i < chineseNumber.length; i++) {
					const char = chineseNumber[i];
					const number = this.chineseNumberMap[char];
					if (typeof number !== 'undefined') {
						if (number < 10) {
							currentNumber = currentNumber * 10 + number;
							if (currentNumber == 101) {
								currentNumber = 11;
							}
							if (currentNumber == 102) {
								currentNumber = 12;
							}
							if (currentNumber == 103) {
								currentNumber = 13;
							}
							if (currentNumber == 104) {
								currentNumber = 14;
							}
							if (currentNumber == 105) {
								currentNumber = 15;
							}
							if (currentNumber == 106) {
								currentNumber = 16;
							}
							if (currentNumber == 107) {
								currentNumber = 17;
							}
							if (currentNumber == 108) {
								currentNumber = 18;
							}
							if (currentNumber == 109) {
								currentNumber = 19;
							}
						} else {
							if (currentNumber === 0) currentNumber = number;
							else {
								currentNumber *= number;
								result += currentNumber;
								currentNumber = 0;
							}
						}
					} else {
						if (currentNumber !== 0) {
							result += currentNumber;
							currentNumber = 0;
						}
					}
				}
				result += currentNumber;
				return result;
			},
		}
	};
</script>
<style>
	.inpbox {
		margin-top: 20rpx;
		width: 100%;
		height: 500rpx;
	}
	textarea {
		width: 100%;
		height: 100%;
		padding: 15rpx;
		padding-top: 20rpx;
		letter-spacing: 2rpx;
		border-radius: 12rpx;
		background: #F4F5F6;
	}
</style>

输入内容
在这里插入图片描述
输出转换结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值