我正在寻找一个Java示例来检查用户输入的双精度数值是否包含2个小数位,例如,输入的99.99将返回有效,输入99.9或99.999将返回无效。验证以检查小数点后两位的双精度数
0
A
回答
2
5
Double d = 234.12413;
String[] splitter = d.toString().split("\\.");
splitter[0].length(); // Before Decimal Count
int decimalLength = splitter[1].length(); // After Decimal Count
if (decimalLength == 2)
// valid
else
// invalid
对于亨利的问题
double d1 = 0.50;
double d2 = d1%1;
DecimalFormat df = new DecimalFormat("#.00");
int decimalLength = (df.format(d2).length()-1);
if (decimalLength == 2)
//valid
else
// invalid
注:df.format(d2)
回报.50
,所以长度是3
0
还有一个办法:
//assert that the string is valid number
String num = "99.99"; // I assume that is `String` because entered by user and not yet converted to `double`
int i = num.lastIndexOf('.');
if(i != -1 && num.substring(i + 1).length() == 2) {
System.out.println("The number " + num + " has two digits after dot");
}
*增加 如果你的魔杖使用本地具体decimal separator
使用以下expession代替'.'
的结果。
DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance();
DecimalFormatSymbols symbols = format.getDecimalFormatSymbols();
//symbols.getDecimalSeparator() == '.';
相关问题
- 1. C++舍入双精度小数点后两位数
- 2. 打印双精度小数点前后两位数
- 3. 限制一个双精度到小数点后两位的小数位
- 4. 如何将双精度转换为小数点后两位?
- 5. 使用双精度到小数点后两位
- 6. 小数点后的双精度
- 7. 双精度变量小数点后4位数
- 8. 将双精度值格式化为小数点后1位
- 9. 圆形双到小数点后两位
- 10. 限制双到小数点后两位
- 11. 检查两个浮点数/双精度值是否相等
- 12. 获取双精度值的小数位
- 13. 截断双精度到2位小数?
- 14. 从双精度除去小数点后的尾部零点
- 15. Java - MySQL |双精度和小数点
- 16. SQL C#双精度小数点
- 17. 如何返回带有两位小数的双精度值?
- 18. 如何在C#中使用双精度型数字获得小数点后两位数的数字?
- 19. 标准双精度IEEE浮点数有多少位的精度?
- 20. 双精度和单精度浮点数?
- 21. .NET Web API返回大量小数位后的双精度值
- 22. 格式化一个双精度到两位小数
- 23. 作为两个双打总和的双双精度浮点数
- 24. 比较楼层/小区后的浮点数/双精度比较
- 25. 验证总数为4位,小数点后只有2位数
- 26. 精确地将浮点数/小数点精确到小数点后3位?
- 27. 获取小数位的精确精度从双在.net 3.5
- 28. 带小数点后精度的struct.unpack
- 29. 指定双精度到另一个带有1个数字的双精度小数点后
- 30. 如何将小数点后两位到小数点后n位?
到目前为止你有什么? – GaryF
SO不是代码工厂! –
只要输入字符串为'String'(然后它很平凡),你只能这样做 – Henry