0

"Hey guys ! I have a question about how can I format some numbers . For example I want the number 33304 to be converted as 333,04 and the number 108100 as 1081,00. The rule is to remain two decimals after comma separator. I tried with javascript format functions but I could not find the right solution. Can you help me with an answer pls?

3
  • 1
    Can you please show us the code what you have tried so far? Commented Jul 10, 2019 at 5:42
  • In angular you can use Custom Pipes for transforming value in this format. Commented Jul 10, 2019 at 5:42
  • I tried with split method and with toFixed() method from javascript . I am on the road and I can't show my code. It's more of a problem of inserting a certain element(",") at a position with the rule of remaining 2 characters at the end . Commented Jul 10, 2019 at 5:52

3 Answers 3

3

Using just JavaScript or TypeScript, you can write:

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

Examples:

num(33304) === '333,04';
num(108100) === '1081,00';
num(101) === '1,01';
num(50) === '0,50';
num(1) === '0,01';
num(0) === '0,00';
Sign up to request clarification or add additional context in comments.

Comments

0

Using Custom Pipes you can achieve this transformation. see the below example :-

//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;    
   }
  } 

Hope it will help.

Comments

0

you can use number formatting method:

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

source:

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

or

use the following one:

var str="33304";

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

console.log(resStr);

2 Comments

he want "," before last two digit.
you are right @SunnyGoel but i thought he can get a idea from there.

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.