0

I have a number 10.625

In JavaScript

10.625.toFixed(2)  //gives 10.63

In Java,

Double.valueOf(new DecimalFormat("###.##").format(Double.valueOf("10.625"))) //gives 10.62

How I can achieve unique output both at client and server side?

Shoaib Chikate
  • 8,665
  • 12
  • 47
  • 70
  • Why do you have this problem ? Are you sure `number` is the right format for you ? – Denys Séguret Dec 25 '14 at 09:25
  • Yes, it is conflicting me on server and client side. – Shoaib Chikate Dec 25 '14 at 09:26
  • first round the number on server side then limit to two decimal place refer this http://stackoverflow.com/a/17072953/795683 – Sain Pradeep Dec 25 '14 at 09:26
  • Well, both are valid. If you're comparing string representations of floating point numbers it means you're doing numerics very wrongly – Denys Séguret Dec 25 '14 at 09:26
  • 1
    There are [various valid IEEE754 rounding modes](http://en.wikipedia.org/wiki/IEEE_floating_point#Roundings_to_nearest). Which one is used doesn't matter in a properly designed application (apart if you're doing Monte-Carlo algorithms) – Denys Séguret Dec 25 '14 at 09:33

4 Answers4

3

This will print 10.63, and the conversion back to Double will be based on this value.

DecimalFormat df = new DecimalFormat("###.##");
df.setRoundingMode(RoundingMode.HALF_UP);
System.out.println(df.format(Double.valueOf("10.625")));
Salman A
  • 262,204
  • 82
  • 430
  • 521
laune
  • 31,114
  • 3
  • 29
  • 42
1

The way to harmonise the view of the number on client and server is to do your processing on the server and have the client display what the server sends it.

Use the Java version on the server, convert to a String, and send that to the client. Then you'll just be doing the conversion once, and won't have the possibility of a conflict.

After all, the client is just supposed to be giving a nice view of what the server has done. Repeating the calculations on the client is not the right way to think about it.

chiastic-security
  • 20,430
  • 4
  • 39
  • 67
0

You could use Math.round(value * 100) / 100 for both java and javascript.

Gnucki
  • 5,043
  • 2
  • 29
  • 44
0
     BigDecimal bd = new BigDecimal("10.625");
    bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);  
    double value = Double.parseDouble(new DecimalFormat(".##").format(bd));
    System.out.println(value);

will also print 10.63

Some important infos to catch :

  • since you never want to know how much digit before . then you can simpy use .##
  • On DecimalFormat ==> .## format will print 0.x0 to 0.x while '0.00' format will print 0.x0 to 0.x0 so i prefer the second format
Fevly Pallar
  • 3,059
  • 2
  • 15
  • 19