小数点后的零添加正数

编程入门 行业动态 更新时间:2024-10-23 20:21:52
本文介绍了小数点后的零添加正数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要给用户,直到数位输入的数字精度。就像如果用户输入一些随机值,并给出他想要的精度,直到三个数字,然后我需要四舍五入的数字,直到小数点后三位。所以我做了这样的事情。

I need to give accuracy of a number entered by user till few digit. like if user enter some random value and gives that he wants accuracy till three digit then I need to round off the digit till three places after decimal. So i did something like this

int index = value.indexOf('.'); if (index >= 0) { String fractional = value.substring(index); if (fractional.length() > decimalPlaces) { floatValue = roundOffDecimals(floatValue, decimalPlaces); } } retVal = new Float(floatValue);

但是,当用户输入一些价值,但不进入为十进制我需要显示它作为零小数位数的惨淡值的值。像15是他的电话号码和3个是他的准确性,然后我需要显示号码15.000

but when user enters some value but do not enters any value as decimal I need to display it as dismal value with zeros as number of decimal places. like for 15 is his number and 3 is his accuracy then I need to display number as 15.000

我不能够小数点后显示为零时,它总是变化。请帮忙。我试图DeciamlFormat DF =新DecimalFormat的(,###);但需要静态值。而我的精度不断变化。

I am not able to display zero after decimal when it always changes. Please help. I tried DeciamlFormat df = new DecimalFormat("",#.##); but takes static value. And my accuracy keeps changing.

任何帮助将AP preciated。

Any help will be appreciated.

推荐答案

您可以创建一个返回您小数的确切格式的方法。下面是一个例子:

You can create a method that returns the exact format for your decimals. Here is an example:

public String formatNumber(int decimals, double number) { StringBuilder sb = new StringBuilder(decimals + 2); sb.append("#."); for(int i = 0; i < decimals; i++) { sb.append("0"); } return new DecimalFormat(sb.toString()).format(number); }

如果您不需要更改小数价值如此频繁,那么您可以将方法更改为类似:

If you don't need to change the decimals value so often, then you can change your method to something like:

public DecimalFormat getDecimalFormat(int decimals) { StringBuilder sb = new StringBuilder(decimals + 2); sb.append("#."); for(int i = 0; i < decimals; i++) { sb.append("0"); } return new DecimalFormat(sb.toString()); }

更多推荐

小数点后的零添加正数

本文发布于:2023-10-14 22:27:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492399.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正数   小数点

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!