[Solved] Javascript toFixed equivalent in java

I am using toFixed(2) in client side(javascript). But in the server side(java) i have to recalculate. how can i do this?

Enquirer: jay


Solution #1:

setScale() of BigDecimal will do it for you on server side

import java.math.BigDecimal;

public class Main{

public static void main(String ar[]){
 float number = 123.123456F;
 BigDecimal numberBigDecimal = new BigDecimal(number);
 numberBigDecimal  = numberBigDecimal .setScale(2, BigDecimal.ROUND_HALF_UP);
Respondent: jmj

Solution #2:

DecimalFormat‘s format method is the equivalent in java to toFixed in javascript.

DecimalFormat decimalFormat = new DecimalFormat("0.##");
Respondent: henryabra

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.