gpt4 book ai didi

angular - 在 Angular 中将数字转换为单词

转载 作者:行者123 更新时间:2023-12-02 02:30:53 27 4
gpt4 key购买 nike

如何将数字转换为 Angular 单词

例如:“1232”到“一千二百三十二”

我是 Angular 新手,有人可以帮我解决这个问题吗?

最佳答案

您可以使用@thank-you here发布的算法并将其转换为管道。

Demo

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'numberToWords'
})
export class NumberToWordsPipe implements PipeTransform {
transform(value: any): string {
if (value && isInteger(value))
return numToWords(value);

return value;
}
}

const isInteger = function(x: any) {
return x % 1 === 0;
}


const arr = x => Array.from(x);
const num = x => Number(x) || 0;
const str = x => String(x);
const isEmpty = xs => xs.length === 0;
const take = n => xs => xs.slice(0,n);
const drop = n => xs => xs.slice(n);
const reverse = xs => xs.slice(0).reverse();
const comp = f => g => x => f (g (x));
const not = x => !x;
const chunk = n => xs =>
isEmpty(xs) ? [] : [take(n)(xs), ...chunk (n) (drop (n) (xs))];
// numToWords :: (Number a, String a) => a -> String
let numToWords = n => {
let a = [
'', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
];
let b = [
'', '', 'twenty', 'thirty', 'forty',
'fifty', 'sixty', 'seventy', 'eighty', 'ninety'
];
let g = [
'', 'thousand', 'million', 'billion', 'trillion', 'quadrillion',
'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion'
];
// this part is really nasty still
// it might edit this again later to show how Monoids could fix this up
let makeGroup = ([ones,tens,huns]) => {
return [
num(huns) === 0 ? '' : a[huns] + ' hundred ',
num(ones) === 0 ? b[tens] : b[tens] && b[tens] + '-' || '',
a[tens+ones] || a[ones]
].join('');
};
// "thousands" constructor; no real good names for this, i guess
let thousand = (group,i) => group === '' ? group : `${group} ${g[i]}`;
// execute !
if (typeof n === 'number') return numToWords(String(n));
if (n === '0') return 'zero';
return comp (chunk(3)) (reverse) (arr(n))
.map(makeGroup)
.map(thousand)
.filter(comp(not)(isEmpty))
.reverse()
.join(' ');
};

关于angular - 在 Angular 中将数字转换为单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65051817/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com