0

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
1
  • Sorry, your question is not clear. Can you post the actual format and the expected format? Commented Jul 20, 2022 at 8:21

5 Answers 5

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

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

1 Comment

Your answer could be improved by using better formatting and more detailed explanation. You can find information on how to write good answers in the help center. Also note that the question uses comma as decimal separator, not dot.
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.