How to format a number in java to given decimal places? I mean a function similar to number.to fixed() in JavaScript | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to format a number in java to given decimal places? I mean a function similar to number.to fixed() in JavaScript

Decimal places

5th Nov 2016, 12:18 AM
Kingstone Job
Kingstone Job - avatar
2 Answers
+ 2
Say you have: double x = 4.24549747; You could use the following line to create a decimal formatter: DecimalFormat df = new DecimalFormat("#.00"); //this causes a floating point number to show only //2 decimal places (note the 2 zeros) Then to format your number do: df.format(x); Then print: System.out.println(x); //prints 4.24
5th Nov 2016, 4:16 AM
Garrett
Garrett - avatar
0
Thanks Garrett, it actually worked in netbeans
11th Nov 2016, 10:23 PM
Kingstone Job
Kingstone Job - avatar