Javascript 从以毫米为单位的长度转换为英尺,再转换为毫米
我有一个小问题,转换成英尺和英寸的长度 我的代码:Javascript 从以毫米为单位的长度转换为英尺,再转换为毫米,javascript,angular,inches,Javascript,Angular,Inches,我有一个小问题,转换成英尺和英寸的长度 我的代码: // input data this.data = 2500; //get feet this.feet = Math.floor(this.data / 304.8); //get inches let feetrestinmm = this.data - this.feet * 304.8; this.inches = Math.floor(feetrestinmm / 25.4); //get fraction in
// input data
this.data = 2500;
//get feet
this.feet = Math.floor(this.data / 304.8);
//get inches
let feetrestinmm = this.data - this.feet * 304.8;
this.inches = Math.floor(feetrestinmm / 25.4);
//get fraction inches
let inchesrestinmm = feetrestinmm - this.inches * 25.4;
this.toFraction(inchesrestinmm / 25.4);
//back to mm
this.mmValueOut = this.fractionToNumber(this.inchesFraction1 + '/' + this.inchesFraction2) + (this.inches * 25.4) + (this.feet * 304.8);
所以我得到的2500mm的结果是8英尺2英寸和54/127。
但是分数很奇怪。在a中,分数为27/64。
若我计算回mm,我得到的小于输入值
有人能告诉我我做错了什么吗?@Maryannah是对的。要获得正确的值,您应该使用
Math.round
而不是Math.floor
,并使用如下方法减少toFraction
函数的返回值:
function ggT(a, b) {
var c, d;
c = a; d = b;
while ( c != d ) {
if ( c < d )
d = d - c
else c = c - d
}
return(c);
27 + 27 = 54 ---- 64 + 64 = 128. 你得到的分数只是在线分数的未缩减版本(减去你可能在计算中犯的一些错误-例如,
Math.floor
)。可能是angular或在线转换器正在对结果进行四舍五入。谢谢,但我得到了与Math.floor和Without reduce相同的结果:-(
function ggT(a, b) {
var c, d;
c = a; d = b;
while ( c != d ) {
if ( c < d )
d = d - c
else c = c - d
}
return(c);
toFraction(x: number)
{
let tolerance = 1.0E-6;
let h1 = 1;
let h2 = 0;
let k1 = 0;
let k2 = 1;
let b = x;
do {
let a = Math.floor(b);
let aux = h1;
h1 = a * h1 + h2;
h2 = aux;
aux = k1;
k1 = a * k1 + k2;
k2 = aux;
b = 1 / (b - a);
} while (Math.abs(x - h1 / k1) > x * tolerance);
let reducer = ggT(h1,k1)
this.inchesFraction1 = (h1/reducer);
this.inchesFraction2 = (k1/reducer);
}