"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?
-
1Can you please show us the code what you have tried so far?Tushar Gupta– Tushar Gupta2019-07-10 05:42:22 +00:00Commented Jul 10, 2019 at 5:42
-
In angular you can use Custom Pipes for transforming value in this format.Sunny Goel– Sunny Goel2019-07-10 05:42:55 +00:00Commented 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 .Razvan Stoica– Razvan Stoica2019-07-10 05:52:59 +00:00Commented Jul 10, 2019 at 5:52
Add a comment
|
3 Answers
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
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
Sunny Goel
he want "," before last two digit.
akash
you are right @SunnyGoel but i thought he can get a idea from there.