如何在Java中将双精度值截断为给定的小数位?
简而言之,截断意味着砍掉数字的小数部分。一种通过将所有小数位删除超过某个点而不进行四舍五入来近似十进制数的方法。
给定一个双精度值和一个小数位,将值截断到给定的小数点。
例子:
Input: val = 3.142857142857143
Decimal point = 3
Output = 3.142
Upto 3 decimal places
方法 1:在数学上使用:
- 通过乘以 10^n 将给定值的小数移至给定小数点
- 取数字的地板并将数字除以 10^n
- 最终值是截断后的值
Java
// Java program to truncate the double value to
// a particular decimal point
import java.io.*;
class GFG {
static void change(double value, int decimalpoint)
{
// Using the pow() method
value = value * Math.pow(10, decimalpoint);
value = Math.floor(value);
value = value / Math.pow(10, decimalpoint);
System.out.println(value);
return;
}
// Main Method
public static void main(String[] args)
{
double firstvalue = 1212.12131131;
int decimalpoint = 4;
change(firstvalue, decimalpoint);
double secondvalue = 3.142857142857143;
int decimalpoint2 = 3;
change(secondvalue, decimalpoint2);
}
}
Java
// Java program to truncate the double
// value using string matching
import java.io.*;
class GFG {
public static void main(String[] args)
{
double firstvalue = 1212.12131131;
// decimal point
int decimalpoint = 6;
// convert the double value in string
String temp_value = "" + firstvalue;
String string_value = "";
int counter = -1;
for (int i = 0; i < temp_value.length(); ++i) {
// checking the condition
if (counter > decimalpoint) {
break;
}
else
if (temp_value.charAt(i) == '.') {
counter = 1;
}
else if (counter >= 1) {
++counter;
}
// converting the number into string
string_value += temp_value.charAt(i);
}
// parse the string
double new_value = Double.parseDouble(string_value);
System.out.println(new_value);
}
}
输出
1212.1213
3.142
方法二:使用字符串匹配方法
- 将数字转换为字符串
- 当“.”时启动计数器变量在字符串中找到
- 将计数器递增到小数点
- 存储新的String并以double格式解析
Java
// Java program to truncate the double
// value using string matching
import java.io.*;
class GFG {
public static void main(String[] args)
{
double firstvalue = 1212.12131131;
// decimal point
int decimalpoint = 6;
// convert the double value in string
String temp_value = "" + firstvalue;
String string_value = "";
int counter = -1;
for (int i = 0; i < temp_value.length(); ++i) {
// checking the condition
if (counter > decimalpoint) {
break;
}
else
if (temp_value.charAt(i) == '.') {
counter = 1;
}
else if (counter >= 1) {
++counter;
}
// converting the number into string
string_value += temp_value.charAt(i);
}
// parse the string
double new_value = Double.parseDouble(string_value);
System.out.println(new_value);
}
}
输出
1212.121311