Angular中字符串转double方法及金额转BRL货币数字实现
Hey there! Let's work through your two questions step by step:
1. Fixing BRL Currency Formatting for Your Invoice Amount
It looks like your payment API is returning the invoice amount in cents (the smallest unit of Brazilian Real), which is a standard practice for payment systems to avoid floating-point precision issues. Right now, you're passing 10500 (which equals 10500 cents) directly to the currency pipe, which interprets it as 10500 full reais—hence the unexpected $ 10,500.00 output.
To get the correct $ 105.00 result, you just need to convert the cent-based integer to a reais-based number first by dividing by 100, then apply the currency pipe:
{{ (signature.invoice.amount / 100) | currency: 'BRL': true }}
If you want to match the official Brazilian formatting (using R$ instead of $ and commas for decimals), you can add the pt-BR locale (just make sure you've registered the locale in your Angular app first):
{{ (signature.invoice.amount / 100) | currency: 'BRL': true: '1.2-2': 'pt-BR' }}
This will output R$ 105,00, which is the standard BRL display format in Brazil.
2. Converting Strings to Double in Angular (TypeScript)
In Angular, since we use TypeScript for application logic, converting a string to a double (floating-point number) is straightforward. Here are the most common, reliable methods:
Using
parseFloat(): This function parses a string and returns a floating-point number, perfect for handling values with decimal points:const stringAmount = '105.00'; const doubleAmount = parseFloat(stringAmount); // Result: 105.0Using the
Number()constructor: Works seamlessly for both integer and floating-point string values:const stringAmount = '105.00'; const doubleAmount = Number(stringAmount); // Result: 105.0Using the unary
+operator: A concise shorthand for converting strings to numbers:const stringAmount = '105.00'; const doubleAmount = +stringAmount; // Result: 105.0
Quick Validation Tip:
Always check if the conversion was successful to avoid NaN (Not a Number) errors. Use isNaN() to validate:
const stringAmount = 'invalid-value'; const doubleAmount = parseFloat(stringAmount); if (isNaN(doubleAmount)) { console.error('Invalid number string provided!'); // Add your error handling logic here }
内容的提问来源于stack exchange,提问作者Luiz Ricardo Cardoso

