繁体   English   中英

javascript / typescript / angular中的逗号分隔符

[英]Comma separator in javascript/typescript/angular

“大家好!我对如何格式化一些数字有疑问。例如,我希望将33304转换为333,04,将108100转换为1081,00。规则是在逗号分隔符后保留两位小数。我尝试使用javascript格式函数,但找不到正确的解决方案,能否为我提供解答?

仅使用JavaScript或TypeScript,您可以编写:

function format(n) {
  (n / 100).toFixed(2).replace('.', ',');
}

例子:

num(33304) === '333,04';
num(108100) === '1081,00';
num(101) === '1,01';
num(50) === '0,50';
num(1) === '0,01';
num(0) === '0,00';

您可以使用数字格式设置方法:

function formatNumber(num) {
      return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
    }

    console.info(formatNumber(2665)) // 2,665
    console.info(formatNumber(102665)) // 102,665
    console.info(formatNumber(111102665)) // 111,102,665

来源

https://blog.abelotech.com/posts/number-currency-formatting-javascript/

要么

使用以下之一:

var str="33304";

var resStr=str.substring(0,str.length-2)+","+str.substring(str.length-2);

console.log(resStr);

使用自定义管道可以实现此转换。 参见下面的例子:

//Component 

import {Component} from '@angular/core';

@Component({
  'selector' : 'app-sample' ,
   template : '  <p>  Number   {{sampleValue | convertPipe}} '
})

export class SampleComponent{
  public sampleValue = 33300;

}

// custom Pipe

 import {Pipe} from '@angular/core'; 

 @Pipe(
   {name: 'convertPipe'}
   )
 export class ConvertPipe{
   transform(value: number){
       let temp1 , temp2 , returnValue;
       temp1 = value/100;
       temp2 = value%100;

       if(temp2 != 0){
          returnValue = temp1 + ',' +temp2;
       } else{
             returnValue = temp1 + ',00';
        }
     return returnValue;    
   }
  } 

希望它会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM