簡體   English   中英

將 Python 浮點數轉換為 C# 十進制數

[英]Convert Python floating-point into C# decimal

我正在嘗試使用 pythonnet 將 Python 中的浮點數轉換為 C# 中的decimal


假設有一個數字“0.0234337688540165776476565071”。

我嘗試了兩種方式:

  1. 使用浮動()
from System import Decimal
from decimal import Decimal as PyDecimal
Decimal(PyDecimal("0.0234337688540165776476565071"))

# This lose every number under the floating-point
0
  1. 使用本機 Python 十進制
from System import Decimal from decimal import Decimal as PyDecimal Decimal(PyDecimal("0.0234337688540165776476565071")) # This lose every number under the floating-point 0

我應該怎么辦...?

從您問題中的示例來看,您似乎正在嘗試將字符串轉換為System.Decimal 為此, System.Decimal有一個Parse方法

from System import Decimal

Decimal.Parse("0.0234337688540165776476565071")

注意:您可能還需要根據您的場景傳遞CultureInfo.InvariantCulture

如果您將字符串轉換為 python 浮點數,那么它將被截斷為 64 位,您將失去精度。 您將不得不為System.Decimal使用不同的構造函數 例如:

public Decimal (int lo, int mid, int hi, bool isNegative, byte scale);

跳過驗證,它可能看起來像

from System import Decimal
from System import Int32, Boolean, Byte

def str_to_csp_decimal(number: str) -> Decimal:
    """ convert a string to a C# Decimal """
    is_negative = number[0] == "-"
    abs_value = number[1:] if is_negative else number

    has_fraction = "." in abs_value 
    if has_fraction:
        integer, fraction = abs_value.split(".")
        scale = len(fraction)                # denominator = 10 ** scale
        numerator = int(integer + fraction)  # no precision loss for integers
    else:
        scale = 0                            # denominator == 1
        numerator = int(abs_value)
    
    assert numerator < (2 << 96), "Decimal only has 96 bits of precision"

    # split the numerator into the lower, mid, and high 32 bits
    mask = 0xFFFFFFFF
    low = Int32(numerator & mask)
    mid = Int32((numerator >> 32) & mask)
    high = Int32((numerator >> 64) & mask)

    return Decimal(low, mid, high, Boolean(is_negative), Byte(scale))

str_to_csp_decimal("0.0234337688540165776476565071").ToString()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM