如何在Angular中把数字转换为字符串?

473 阅读2分钟

这篇文章介绍了在Angular应用程序中把数字转换成文字的方法,例如,输入123,输出为一二三。

我们有多种方法可以将数字转换为字符串:

  1. 使用数转字npm包
  2. 使用逻辑的自定义解决方案。

这篇博客涵盖了npm包在Angular应用程序中的数字到文字的用法。

前提条件

  • Angular cli安装
  • 类型脚本
  • node和npm

安装Angular cli版本

首先,请通过命令中的-version选项确保ng --version command 。如果ng命令没有安装,并给出ng command not found error ,请安装@angular/cli

npm install -g @angular/cli

在Angular cli安装后,ng命令应该可以工作并输出版本。

这将列出Angular cli的版本。

B:\blog\jswork\angular-number-words>ng --version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 11.0.5
Node: 10.16.3
OS: win32 x64

Angular: 11.0.5
... animations, cli, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, router
Ivy Workspace: Yes

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1100.5
@angular-devkit/build-angular   0.1100.5
@angular-devkit/core            11.0.5
@angular-devkit/schematics      11.0.5
@schematics/angular             11.0.5
@schematics/update              0.1100.5
rxjs                            6.6.3
typescript                      4.0.5

使用带有new选项的ng命令,创建一个新的应用程序

ng new angular-number-words

这将创建一个包含所有必要文件的angular 11应用程序。

一旦应用程序被创建,安装数字到文字的依赖项

npm install number-to-words --save-dev
npm install @types/number-to-words --save-dev

安装完成后,它在package.json 中产生两个条目。

{
        "@types/number-to-words": "^1.2.0",
        "number-to-words": "^1.2.4",
}

在Angular中将数字转换为字符串

在模板文件中,app.component.html

  • 创建了具有双向绑定的文本框
  • 添加了带有点击事件的按钮。
  • 一旦点击发生,从文本框中取出数字并转换为字符串,然后输出到页面。

Angular Convert Number to word example

 {{outputWords}}

Convert to String

在组件中,app.component.ts

请导入数字到文字的转换器,如下所述,使用converter.toWords(number) 来转换为字符串


import { Component } from '@angular/core';
import * as converter from 'number-to-words';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  mynumber:number=0;
  outputWords=''
  convertToWord(){
    this.outputWords= converter.toWords(this.mynumber);

  }
}

输入是10000000,输出是1000万,输入是409,输出是4009

问题是找不到'数转字'模块的声明文件

第一次,我只安装了number-to-words包,得到的结果是error TS7016: Could not find a declaration file for module 'number-to-words'.

以下是完整的错误描述

Error: src/app/app.component.ts:2:28 - error TS7016: Could not find a declaration file for module 'number-to-words'. 'B:/blog/jswork/angular-number-words/node_modules/number-to-words/src/index.js' implicitly has an 'any'
  Try `npm install @types/number-to-words` if it exists or add a new declaration (.d.ts) file containing `declare module 'number-to-words';`

上述问题是在没有安装@types/number-to-words包时发生的,请安装@types/number-to-words 来解决这个问题。