In Apex, the Double data type is used to store numbers that have decimal places. Think of it like a calculator where you can have numbers like 3.14 or 99.99.
You can create a Double variable and give it a value in a few ways.
// Declare a variable called 'price' and set its value
Double price = 10.50;
// Declare a variable first, then set its value later
Double quantity;
quantity = 5.0;
// Use the Double.valueOf() method to convert text or another number to a Double
Double taxRate = Double.valueOf('0.07'); // Convert text '0.07' to a Double
Double itemCount = Double.valueOf(10); // Convert the number 10 to a Double (becomes 10.0)
Notice that even if you set a Double to a whole number like 10, Apex will still store it with a decimal, like 10.0.
You can use Double variables to do basic calculations:
Double item1Price = 5.99; Double item2Price = 12.50; // Addition (+) Double subtotal = item1Price + item2Price; // subtotal will be 18.49 Double totalItems = 25.0; Double itemsSold = 10.0; // Subtraction (-) Double itemsRemaining = totalItems - itemsSold; // itemsRemaining will be 15.0 Double numberOfOranges = 3.0; Double pricePerOrange = 0.75; // Multiplication (*) Double costOfOranges = numberOfOranges * pricePerOrange; // costOfOranges will be 2.25 Double totalDistance = 100.0; // in kilometers Double timeTaken = 2.5; // in hours // Division (/) Double averageSpeed = totalDistance / timeTaken; // averageSpeed will be 40.0
Both Double and Decimal can store numbers with decimals, but they are used for different things, especially in Salesforce:
For now, focus on using Double for simple numbers with decimal places and basic math.
By practicing with these basics, you'll get comfortable using Double values in your Apex code!
// Declare a variable called 'price' and set its value
Double price = 10.50;
// Declare a variable first, then set its value later
Double quantity;
quantity = 5.0;
// Use the Double.valueOf() method to convert text or another number to a Double
Double taxRate = Double.valueOf('0.07'); // Convert text '0.07' to a Double
Double itemCount = Double.valueOf(10); // Convert the number 10 to a Double (becomes 10.0)
Double item1Price = 5.99; Double item2Price = 12.50; // Addition (+) Double subtotal = item1Price + item2Price; // subtotal will be 18.49 Double totalItems = 25.0; Double itemsSold = 10.0; // Subtraction (-) Double itemsRemaining = totalItems - itemsSold; // itemsRemaining will be 15.0 Double numberOfOranges = 3.0; Double pricePerOrange = 0.75; // Multiplication (*) Double costOfOranges = numberOfOranges * pricePerOrange; // costOfOranges will be 2.25 Double totalDistance = 100.0; // in kilometers Double timeTaken = 2.5; // in hours // Division (/) Double averageSpeed = totalDistance / timeTaken; // averageSpeed will be 40.0