简体   繁体   English

使用 Symfony 5 中的 FOSRestBundle 转换单个属性以进行响应

[英]Convert single property for response with the FOSRestBundle in Symfony 5

I'm working with numbers with a lot of decimal places in my symfony application.我在我的 symfony 应用程序中处理带有很多小数位的数字。 In my doctrine entity I have for example this property:在我的 doctrine 实体中,我有例如这个属性:

/**
 * @ORM\Column(type="float")
 */
private float $value;

In my mysql database I have this value for example: 0.00000000020828579949508在我的 mysql 数据库中,我有这个值,例如:0.00000000020828579949508

When I dump that in PHP I'm getting this: float(9.3722658865184E-7).当我在 PHP 中转储它时,我得到了这个:float(9.3722658865184E-7)。 I also made an API with the FOSRestBundle.我还用 FOSRestBundle 制作了一个 API。 In that API I want to return the value not in exponential form with at least 12 of it's decimal places.在那个 API 中,我想返回不是指数形式的值,至少有 12 个小数位。 I think in that case I have to provide the value as string, correct?我认为在这种情况下,我必须将值提供为字符串,对吗? I figured out that I can convert it to string with something like this: sprintf("%.12f", $myEntity->getValue()) .我发现我可以使用以下方式将其转换为字符串: sprintf("%.12f", $myEntity->getValue()) But I have two questions now:但我现在有两个问题:

  1. How can I convert a single property for response with the FOSRestBundle?如何使用 FOSRestBundle 转换单个属性以进行响应? So that I return the "value" property as string, even if it is a float normally.所以我将“值”属性作为字符串返回,即使它通常是一个浮点数。
  2. Is there a general best practice or any tips to work with such numbers in symfony, doctrine and the FOSRestBundle?在 symfony、doctrine 和 FOSRestBundle 中是否有使用此类数字的一般最佳实践或任何提示?

Right now this is my controller action:现在这是我的 controller 操作:

public function getData(): Response
{
    $repository = $this->getDoctrine()->getRepository(MyEntity::class);
    $data = $repository->findAll();

    return $this->handleView($this->view($data));
}
  1. Assuming you are using Symfony version 3.x , you can use the JMS @Expose and @Accessor annotations to control how your entity property is serialized into response data.假设您使用的是 Symfony 版本3.x ,您可以使用 JMS @Expose@Accessor注释来控制您的实体属性如何序列化为响应数据。 More info here .更多信息在这里 However, consider that JMS is bypassed if all you want is to pass your entity to the Twig template rendering engine.但是,如果您只想将实体传递给 Twig 模板渲染引擎,请考虑绕过 JMS。

  2. The Doctrine float column type is the correct type to use when handling larger sized floating point numbers such as yours. Doctrine float列类型是处理较大的浮点数(例如您的浮点数)时使用的正确类型。 Your issue is more related to the scientific notation that PHP is designed to use in order to represent these large floats.您的问题与 PHP 旨在用于表示这些大浮点数的科学记数法更相关。 Allowing arithmetic such as 2.1E-10 + 2.2E-9 , but also requiring extra steps to convert their notation to a perhaps more human friendly readable form by using functions such as sprintf and number_format .允许诸如2.1E-10 + 2.2E-9类的算术运算,但还需要额外的步骤,通过使用诸如sprintfnumber_format之类的函数将它们的符号转换为可能对人类更友好的可读形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM