'How to separate thousands with comma in angular 2
in angular 2 or 4 I want numbers be separated in thousand by comma, when it is in input and user typing and when it is just print it. Do you have any idea or solution to share it? Thank you guys in advance.
Solution 1:[1]
You have 2 options here:
Pipes (for texts without user interaction)
- For texts (simply displaying something), you can simply use Angular's built-in Decimal Pipe
@Component({
selector: 'number-pipe',
template: `<div>
<!--output '25,000.00'-->
<p>{{mynumber | number:'5.2-2'}}</p>
<!--output '25 000,00'-->
<p>{{mynumber | number:'5.2-2':'fr'}}</p>
</div>`
})
export class NumberPipeComponent {
mynumber: number = 2500000;
}
The '5.2.2' part responds to a rule defined like:
{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
And be aware that a different locale produces different results in terms of using commas or dots when formatting.
Masks (for inputs where the number gets formatted as the user types)
- If you want to format the number as the user types inside an
<input>you'll need to use a masking library or a formatter solution like this npm package or similar.
After installing the package npm install ng2-currency-mask --save, you have to add it to your Module via imports
import { CurrencyMaskModule } from "ng2-currency-mask";
@NgModule({
imports: [
...
CurrencyMaskModule
],
declarations: [...],
providers: [...]
})
export class AppModule {}
And finally implement it like:
<input currencyMask [(ngModel)]="value" [options]="{ prefix: 'R$ ', thousands: '.', decimal: ',' }"/>
Make sure you check all the different options the package offers.
Solution 2:[2]
Just add this pipe {{ mynumber | number:0 }}. It will specify that your value is a number. So, it will be comma separated, and then the "0" specifies there're no decimals.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | dloeda |
