簡體   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