51853

How to format a variable of double type

I have a variable of double type representing a value of about 34.323423423123456. I'd like to format it to have only two decimal places (e.g. 34.32), rounded properly; e.g. 2.229934345 would become 2.23.

I am new to Java and none the tricks I know from C# worked.

Answer1:

Related to this Question use DecimalFormat setRoundingMode

Answer2:

Here's an example format string, I believe it correctly rounds the resulting value. See Markus' post if you need more control over the rounding or format:

String.format("%.2f", 2.229934345);

Recommend

  • some none IE browsers are showing true for IE6 Browser detection
  • Roboletric 4.0.1 keeps throwing Resources$NotFoundException on buildActivity
  • How to let maven resolve transitive dependency for local dependency
  • DropShadowPanel adapt to button template style
  • How to define matching axis notches from existing “step list”
  • Why Is jQuery Not Submitting This Form? (Or What Have I Done Wrong? :-p)
  • different results with and without SSE ( float arrays multiplication)
  • Zend framework 2 : Add different authentication adapter for two different modules
  • How to override jQuery promise callback
  • custom string delimiters stringtemplate-4
  • Insertion large number of Entities into SQL Server 2012 [duplicate]
  • Lua: Line breaks in strings
  • Configure nginx to return different files to different authenticated users with the same URI
  • LESS CSS how to modify parent property in mixin
  • Angular2 - Template reference inside NgSwitch
  • VBA Excel, loop through variables
  • For loop with if condition on multiple R functions
  • Defined variables not working in javascript files when I use getScript
  • Is there a way to save the selected text and highlight it again once the page is refreshed?
  • ThreadStatic in asynchronous ASP.NET Web API
  • Scipy Leastsq Optional Output Variable (Mesg)
  • Scala multiline string placeholder
  • Z3: Convert between FP and BitVector?
  • Assign variable to the value in HTML
  • Jackson Parser: ignore deserializing for type mismatch
  • Converting a WriteableBitmap image ToArray in UWP
  • D3 nodes and links from JSON with nested arrays of children
  • OpenGL ES texture problem, 4 duplicate columns and horizontal lines (Android)
  • Linq Objects Group By & Sum
  • Updating server-side rendering client-side
  • Cross-Platform Protobuf Serialization
  • htaccess rewriting URLs with multiple forward slashes
  • Weird JavaScript statement, what does it mean?
  • How do you troubleshoot character encoding problems?
  • Buffer size for converting unsigned long to string
  • coudnt use logback because of log4j
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • JaxB to read class hierarchy
  • Binding checkboxes to object values in AngularJs
  • How to Embed XSL into XML