function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Michael MMichael M 

how to display only first 2 digits after decimal in apex

Hello, if i have a decimal like
decimal dec = 1.234234235345

i ONLY want to display the number with the first 2 digits after the decimal, meaning 1.23. How can I do this in apex?
Best Answer chosen by Michael M
VinayVinay (Salesforce Developers) 
Hi Michael,

Try below snippet.
 
Decimal toround = 3.14159265;
Decimal rounded = toround.setScale(2);
system.debug(rounded);
Check below references.

https://salesforce.stackexchange.com/questions/11686/decimals-in-apex-setting-scale-without-rounding
https://salesforce.stackexchange.com/questions/957/round-a-decimal-to-two-decimal-places
https://www.forcetalks.com/salesforce-topic/how-to-round-the-double-to-two-decimal-places-in-salesforce-apex/

Hope above information was helpful.

Please mark as Best Answer so that it can help others in the future.

Thanks,

All Answers

VinayVinay (Salesforce Developers) 
Hi Michael,

Try below snippet.
 
Decimal toround = 3.14159265;
Decimal rounded = toround.setScale(2);
system.debug(rounded);
Check below references.

https://salesforce.stackexchange.com/questions/11686/decimals-in-apex-setting-scale-without-rounding
https://salesforce.stackexchange.com/questions/957/round-a-decimal-to-two-decimal-places
https://www.forcetalks.com/salesforce-topic/how-to-round-the-double-to-two-decimal-places-in-salesforce-apex/

Hope above information was helpful.

Please mark as Best Answer so that it can help others in the future.

Thanks,
This was selected as the best answer
Suraj Tripathi 47Suraj Tripathi 47
HI Michael,
Greetings!!

The decimal class in the apex has the method called setscale() it is used to set the decimal value to the specific number or places.
Here is the example.
Decimal myValue= 8.8432108523;
Decimal setScaledValue = myDecimal.setscale(2);
the value will now become the '8.84'.
You can also Round-Up the values as per the need.
Here is the link for all the methods of the decimal class.
https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_decimal.htm

If this helped you please mark it as the best answer.
Thank you!
Regards 
Suraj Tripathi.
Michael MMichael M
Thank you both!