将小数转换为 Feet.Inches

Convert decimal into Feet.Inches

我需要能够将标准双精度转换为另一个合理化为 feet.inches 的双精度(或浮点数)。读取此输出的工具会读取 .作为 "feet" 以及作为 "inches".

之后的任何内容

该工具将 1.12 读数为 2 英尺,因为它是 1 英尺 12 英寸,这就是我们四舍五入到小数点后一位的原因,除非它恰好是 x 英尺 11 英寸。

此函数的目标是传入标准小数,并通过此特定格式return将其转换为英尺和英寸。

public static string ToDecimalFeetString(double num)
{
    return *new ratio, **as a string**, rounded to one decimal place, unless 11 or 10 inches*
}

ToDecimalFeet(0.4) // returns 0.5 (0.4 feet == 5 inches)
ToDecimalFeet(50.9) // returns 50.11 (50.9 feet == 50 feet and 11 inches)
ToDecimalFeet(10.8) // returns 10.10 (10.8 feet == 10 feet and 10 inches)
ToDecimalFeet(29.1) // returns 29.1 (29.1 feet == 29 feet and ~1 inch, when rounded)
ToDecimalFeet(1.00) // returns 1.00 (1.00 feet == 1 foot and zero inches)

编辑: 这显然需要澄清编辑,所以这里是:

提到了一些评论 "Why use imperial?" - 问得好,虽然此转换是针对使用 feet.inches 的完全独立的(生产)工具 - 所以这就是我们必须要做的。

"What if you need to return x feet and 10 inches?" 这是一个很好的问题,对于这种情况,我们将 return x.10 -- 是的,它的值也与 x.1 完全相同,我们将 return 一英寸,但单独的工具读取它们的方式不同,这让我犯了一个愚蠢的错误。

我们实际上是 return 字符串,而不是双精度数。所以打印“0.10”和“0.1”是完全可以的,因为它们与其他工具的值完全不同,对于造成的混淆我深表歉意。我在上面的方法中已经体现了这一点。

编辑 2:修复格式错误

一个简单的方法是获取输入数字,得到 "whole" 部分(不会改变),然后分别得到 "decimal" 部分并将其乘以 12 .然后我们可以将return这些组合成一个字符串:

public static string ToDecimalFeet(double num)
{
    var wholePart = Math.Truncate(num);
    var decimalPart = num - wholePart;
    var inches = Math.Round(12 * decimalPart);
    return $"{wholePart}.{inches}";
}

或者简单地说:

public static string ToDecimalFeet(double num)
{
    return $"{Math.Truncate(num)}.{Math.Round(12 * (num - Math.Truncate(num)))}";
}