[英]Typescript Format String to ##,##
I have been going through this method to convert string to ##,## format.我一直在通过这种方法将字符串转换为##,##格式。 I was wondering is there a more simple way to achieve this?我想知道有没有更简单的方法来实现这一点?
return new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
.format(Number(value.replace(',', '.')));
For example I want the below actual and expected format:例如,我想要以下实际和预期格式:
1 --> 1,00
12 --> 12,00
12,3 --> 12,30
12,34 --> 12,34
You can simply use the toFixed(2) javascript native function.您可以简单地使用 toFixed(2) javascript 原生函数。
Example : parseFloat("9.2").toFixed(2) --> 9.20示例:parseFloat("9.2").toFixed(2) --> 9.20
You can try this out.你可以试试这个。 I checked this for all your scenarios.我检查了你所有的场景。 This works fine.这工作正常。
function formatNumber(num){ return parseFloat(num.replaceAll(',','.')).toFixed(2).replaceAll('.',','); } console.log(formatNumber('12')); console.log(formatNumber('12,3')); console.log(formatNumber('12,34'));
Hope this answers your question.希望这能回答你的问题。
Thanks.谢谢。
function format(num_as_string) { return Number(num_as_string.replace(',', '.')).toFixed(2); } console.log(format('12')); console.log(format('12,3')); console.log(format('12,34'));
I hope I understood the question correctly我希望我正确理解了这个问题
Try this way, by using DecimalPipe,尝试这种方式,通过使用 DecimalPipe,
import { Component, OnInit } from '@angular/core';
import { DecimalPipe } from '@angular/common';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'newp1';
n1 = '1'; // 1 --> 1,00
n2 = '12'; // 12 --> 12,00
n3 = '13,2' // 12,3 --> 12,30
n4 = '13,34' // 13,34 --> 12,34
constructor(private decimal: DecimalPipe) {}
ngOnInit(): void {
console.log(this.transformValue(this.n1));
console.log(this.transformValue(this.n2));
console.log(this.transformValue(this.n3));
console.log(this.transformValue(this.n4));
}
transformValue(num: string) {
return (this.decimal.transform(num.replace(',', '.'), '1.2-2', 'en'))?.replace('.', ',');
}
}
result:结果:
1,00
12,00
13,20
13,34
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.