Javascript toFixed在java中的等价物
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10631813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript toFixed equivalent in java
提问by jay
I am using toFixed(2) in client side(javascript). But in the server side(java) i have to recalculate. how can i do this?
我在客户端(javascript)中使用 toFixed(2)。但是在服务器端(java)我必须重新计算。我怎样才能做到这一点?
回答by Jigar Joshi
setScale()
of BigDecimal
will do it for you on server side
setScale()
的BigDecimal
会在服务器端为你做
import java.math.BigDecimal;
public class Main{
public static void main(String ar[]){
float number = 123.123456F;
BigDecimal numberBigDecimal = new BigDecimal(number);
System.out.println(numberBigDecimal);
numberBigDecimal = numberBigDecimal .setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(numberBigDecimal);
}
}
回答by henryabra
DecimalFormat's formatmethod is the equivalent in java to toFixed in javascript.
DecimalFormat的format方法在 java 中等效于 javascript 中的 toFixed。
DecimalFormat decimalFormat = new DecimalFormat("0.##");
System.out.println(decimalFormat.format(3.1000565));