SlideShare uma empresa Scribd logo
1 de 32
Baixar para ler offline
How to count money
and not lose it
Piotr Horzycki
www.peterdev.pl | twitter.com/peterdevpl
System.out.println(0.10 + 0.20);
0.30000000000000004
Bugs...
if (parseInt(amount) > 0) {
/* proceed with payment */
} else {
/* disable payment button */
}
Why does 0.5 not work?
Bugs...
How does IEEE-754 work?
“A large proportion of the computers in this world
manipulate money, so it's always puzzled me that
money isn't actually a first class data type in any
mainstream programming language. The lack of a
type causes problems, the most obvious surrounding
currencies. (...) The more subtle problem is with
rounding. Monetary calculations are often rounded to
the smallest currency unit. When you do this it's easy to
lose pennies (or your local equivalent) because of
rounding errors.
The good thing about object-oriented programming is
that you can fix these problems by creating a Money
class that handles them. Of course, it's still surprising
that none of the mainstream base class libraries
actually do this.”
https://martinfowler.com/eaaCatalog/money.html
JavaMoney “Moneta”: implementation of the Money pattern
(JSR-354)
Money amount1 = Money.of(123.45, "EUR");
Money amount2 = Monetary.getAmountFactory(Money.class)
.setCurrency("EUR")
.setNumber(123.45)
.create();
“Monetary values are a key feature of many applications, yet the JDK
provides little or no support. The existing java.util.Currency class is
strictly a structure used for representing current ISO-4217 currencies,
but not associated values or custom currencies. The JDK also provides
no support for monetary arithmetic or currency conversion, nor
for a standard value type to represent a monetary amount.”
https://download.oracle.com/otndocs/jcp/money_currency-1_0-fr-eval-spec/
public final class Money implements MonetaryAmount,
Comparable<MonetaryAmount>, Serializable {
/**
* The currency of this amount.
*/
private final CurrencyUnit currency;
/**
* the {@link MonetaryContext} used by this instance, e.g. on division.
*/
private final MonetaryContext monetaryContext;
/**
* The numeric part of this amount.
*/
private final BigDecimal number;
/* ... */
}
Money amount1 = Money.of(123.45, "EUR");
Money amount2 = Money.of(43.21, "EUR");
Money amount3 = amount1.add(amount2);
Money amount4 = amount1.subtract(amount2);
Money amount5 = amount1.multiply(1.23);
Money amount6 = amount1.divide(2);
Money amount7 = amount1.remainder(3);
Basic money arithmetics
final Money amount1 = Money.of(123.45, "EUR");
final Money amount2 = Money.of(123.45, "USD");
amount1.isEqualTo(amount2); // false
amount1.isGreaterThan(amount2); // MonetaryException
Comparing money objects
final Money[] amounts = new Money[] {
Money.of(10, "EUR"),
Money.of(20, "EUR")
};
final MonetarySummaryStatistics statistics =
DefaultMonetarySummaryStatistics
.of(Monetary.getCurrency("EUR"));
Arrays.stream(amounts).forEach(statistics::accept);
System.out.println(statistics.getSum().getNumber());
Statistics: sum, min, max, average...
Immutability
final Money jimPrice = Money.of(25.00, "EUR");
final Money hannahPrice = jimPrice;
final Money coupon = Money.of(5, "EUR");
// wrong
jimPrice.subtract(coupon);
jimPrice.isEqualTo(hannahPrice); // true!
// correct
final Money jimDiscountedPrice = jimPrice.subtract(coupon);
jimDiscountedPrice.isLessThan(jimPrice); // true
$jimPrice and $hannahPrice are immutable value objects
Database
INT, BIGINT…
VARCHAR...
DECIMAL (MySQL)
NUMERIC (Oracle)
FLOAT, DOUBLE...
Database
INT, BIGINT…
VARCHAR...
DECIMAL (MySQL)
NUMERIC (Oracle)
FLOAT, DOUBLE...
DECIMAL(10, 2)
total decimal
digits places
max 99,999,999.99
Exchange rates...
https://www.bankofengland.co.uk/boeapps/database/Rates.asp
https://en.wikipedia.org/wiki/Redenomination
https://www.theguardian.com/world/2018/aug/20/venezuela-bolivars-hyperinflation-banknotes
https://www.amusingplanet.com/2018/08/hungarys-hyperinflation-worst-case-of.html
Hungary’s hyperinflation in 1946
Converting currencies
final ExchangeRateProvider rateProvider = MonetaryConversions
.getExchangeRateProvider();
final CurrencyConversion conversion = rateProvider
.getCurrencyConversion("CHF");
final Money amountUsd = Money.of(10, "USD");
final Money amountChf = amountUsd.with(conversion);
Save the conversion rate!
$100
€100
£100
¥100
...
Price formatting
$100
€100
£100
¥100
...
100 zł
Price formatting
final Money amount = Money.of(123.45, "EUR");
final MonetaryAmountFormat formatter = MonetaryFormats
.getAmountFormat(Locale.ENGLISH);
System.out.println(formatter.format(amount));
EUR123.45
Price formatting
final Money amount = Money.of(123.45, "PLN");
final MonetaryAmountFormat formatter = MonetaryFormats
.getAmountFormat(new Locale("pl", "PL"));
System.out.println(formatter.format(amount));
123,45 PLN
Price formatting
final Money amount = Money.of(123.45, "PLN");
final MonetaryAmountFormat formatter = MonetaryFormats
.getAmountFormat(
AmountFormatQueryBuilder.of(new Locale("pl", "PL"))
.set(CurrencyStyle.SYMBOL)
.build()
);
System.out.println(formatter.format(amount));
123,45 zł
Price formatting
https://en.wikipedia.org/wiki/Dollar_sign
Rounding
●
https://en.wikipedia.org/wiki/Cash_rounding
(aka Swedish rounding)
●
Polish income tax: round to the nearest whole zloty
Architecture
public final class Invoice {
private final InvoiceId number;
private final CurrencyUnit currency;
private Sender sender;
private Recipient recipient;
private PaymentTerms paymentTerms;
private LocalDate issueDate;
private final List<InvoiceItem> items;
public Invoice addItem(InvoiceItem item) { /* ... */ }
public MonetaryAmount getTotalNetAmount() { /* ... */}
public MonetaryAmount getTotalVatAmount() { /* ... */}
public MonetaryAmount getTotalGrossAmount() { /* ... */ }
/* ... */
}
Architecture
interface InvoiceBuilder {
InvoiceBuilder fromSeller(Contractor seller);
InvoiceBuilder toBuyer(Contractor buyer);
InvoiceBuilder addItem(MonetaryAmount unitPrice, int quantity,
VatRate tax);
/* ... */
Invoice build();
}
Further reading
●
https://www.h-schmidt.net/FloatConverter/IEEE754.html
●
https://martinfowler.com/eaaCatalog/money.html
●
https://download.oracle.com/otndocs/jcp/money_currency-1_0-fr-eval-spec/
●
https://github.com/JavaMoney/
●
https://www.baeldung.com/java-money-and-currency
●
https://github.com/peterdevpl/invoices
Thank you!
Piotr Horzycki
www.peterdev.pl | twitter.com/peterdevpl

Mais conteúdo relacionado

Mais de Piotr Horzycki

Serial(ize) killers, czyli jak popsuliśmy API
Serial(ize) killers, czyli jak popsuliśmy APISerial(ize) killers, czyli jak popsuliśmy API
Serial(ize) killers, czyli jak popsuliśmy APIPiotr Horzycki
 
Mity, które blokują Twoją karierę
Mity, które blokują Twoją karieręMity, które blokują Twoją karierę
Mity, które blokują Twoją karieręPiotr Horzycki
 
Architecture tests: Setting a common standard
Architecture tests: Setting a common standardArchitecture tests: Setting a common standard
Architecture tests: Setting a common standardPiotr Horzycki
 
Software development myths that block your career
Software development myths that block your careerSoftware development myths that block your career
Software development myths that block your careerPiotr Horzycki
 
Software Composition Analysis in PHP
Software Composition Analysis in PHP Software Composition Analysis in PHP
Software Composition Analysis in PHP Piotr Horzycki
 
How to count money using PHP and not lose money
How to count money using PHP and not lose moneyHow to count money using PHP and not lose money
How to count money using PHP and not lose moneyPiotr Horzycki
 
New kids on the block: Conducting technical onboarding
New kids on the block: Conducting technical onboardingNew kids on the block: Conducting technical onboarding
New kids on the block: Conducting technical onboardingPiotr Horzycki
 
Time-driven applications
Time-driven applicationsTime-driven applications
Time-driven applicationsPiotr Horzycki
 
Jak zacząć, aby nie żałować - czyli 50 twarzy PHP
Jak zacząć, aby nie żałować - czyli 50 twarzy PHPJak zacząć, aby nie żałować - czyli 50 twarzy PHP
Jak zacząć, aby nie żałować - czyli 50 twarzy PHPPiotr Horzycki
 

Mais de Piotr Horzycki (9)

Serial(ize) killers, czyli jak popsuliśmy API
Serial(ize) killers, czyli jak popsuliśmy APISerial(ize) killers, czyli jak popsuliśmy API
Serial(ize) killers, czyli jak popsuliśmy API
 
Mity, które blokują Twoją karierę
Mity, które blokują Twoją karieręMity, które blokują Twoją karierę
Mity, które blokują Twoją karierę
 
Architecture tests: Setting a common standard
Architecture tests: Setting a common standardArchitecture tests: Setting a common standard
Architecture tests: Setting a common standard
 
Software development myths that block your career
Software development myths that block your careerSoftware development myths that block your career
Software development myths that block your career
 
Software Composition Analysis in PHP
Software Composition Analysis in PHP Software Composition Analysis in PHP
Software Composition Analysis in PHP
 
How to count money using PHP and not lose money
How to count money using PHP and not lose moneyHow to count money using PHP and not lose money
How to count money using PHP and not lose money
 
New kids on the block: Conducting technical onboarding
New kids on the block: Conducting technical onboardingNew kids on the block: Conducting technical onboarding
New kids on the block: Conducting technical onboarding
 
Time-driven applications
Time-driven applicationsTime-driven applications
Time-driven applications
 
Jak zacząć, aby nie żałować - czyli 50 twarzy PHP
Jak zacząć, aby nie żałować - czyli 50 twarzy PHPJak zacząć, aby nie żałować - czyli 50 twarzy PHP
Jak zacząć, aby nie żałować - czyli 50 twarzy PHP
 

Último

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 

Último (20)

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 

How to count money with Java and not lose it