Home > Mobile >  Typescript Format String to ##,##
Typescript Format String to ##,##

Time:07-20

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

CodePudding user response:

Try toLocaleString method of js it will help you to achieve this format

visit this url it will help you how to use it for different kind of formats

CodePudding user response:

You can simply use the toFixed(2) javascript native function.

Example : parseFloat("9.2").toFixed(2) --> 9.20

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

Try this way, by using 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
  • Related