Reputation:
I need to format numeric values as follows: If a number has no decimal places consider the value. If you have any decimal place format with 4 digits after the "," or "."
Examples:
Do nothing
40
50Leave as follows
4.4 | 4,40000
7.1 | 7.10000
100.1 | 100.10000
1000.2 | 1000.20000
I tried to create an @Pipe But it didn't work out Follows the code I tried to implement
import { Pipe, PipeTransform } from '@angular/core';
import { DecimalPipe } from '@angular/common'
@Pipe({
name: 'bigInteger'
})
export class BigInteger extends DecimalPipe implements PipeTransform {
transform(value: any, args?: any): any {
const format = args[0] ? '1' : '1.4-4';
let result;
result = super.transform(value, format).toString().replace(",",".");
console.log(result);
return result;
}
}
Html:
<td class="text-center">{{valueOrder | bigInteger: valueOrder > 100}}</td>
What is the best solution to my problem?
Upvotes: 3
Views: 5915
Reputation:
Thanks I resolved as way
import { Pipe, PipeTransform } from '@angular/core';
import { DecimalPipe } from '@angular/common'
@Pipe({
name: 'numberPipe'
})
export class DecimalNumberPipe extends DecimalPipe implements PipeTransform {
transform(value: any): any {
let result;
if(value % 1 !== 0) {
result = value.toFixed(4);
} else if(value % 1 === 0){
result = value;
}
return result;
}
}
Upvotes: 0
Reputation: 86
If you want to append 0000 in coma values also, it is necessary that the type of your values should be of string, because without string values you cannot append 0000 in the values.
// my array with the numeric values in string format
let arr=["10", "20", "5.2", "6,7"];
// function which check the value and append 0000
function letsCheckAndChange(arr) {
arr.map((value, index) =>{
if(value.includes(",")) { // to check the coma
arr[index] = value + "0000"
} else {
if(parseInt(value) % 2 != 0) {
arr[index] = value.toString() + "0000";
}
}
})
}
letsCheckAndChange(arr);
document.write(arr);
Upvotes: 0
Reputation: 20014
You could use the number pipe:
<p *ngIf="num % 1 !== 0" >{{num | number:'1.4-4'}}</p>
<p *ngIf="num % 1 === 0">{{mum | number:'1.0-4'}}</p>
And check whether or not the number has a decimal values and display based on the format desired.
Or with a nice ng-template
and the if else
touch
<div>
<p *ngIf="num%1!== 0; else noDecimals" >{{num | number:'1.4-4'}}</p>
<ng-template #noDecimals >decimals<p>{{num }}</p></ng-template>
</div>
Upvotes: 0
Reputation: 1052
You may use the toFixed()
method to do what you need here.
let value = 1.2;
value = value.toFixed(5); // 5 is the number of digits after the decimal
console.log(value);
Upvotes: 1