gpt4 book ai didi

javascript - 在 javascript 中使用按位删除小数的语法帮助

转载 作者:行者123 更新时间:2023-12-02 17:09:06 24 4
gpt4 key购买 nike

尝试在变量更新时对其进行格式化。我想通过使用bitwise operators来做到这一点。我似乎无法理解语法。

目前,数字的最大值为 5.2342340990843,我希望它们的最大深度为 2 位小数。 example code

var app = angular.module('morningharwoodApp', []);
app.controller('MainCtrl', function ($scope, $window) {
$scope.squares = [1,2,3,4,5,6,7,8];
if ($window.DeviceMotionEvent != undefined) {
$window.ondevicemotion = function(event) {
//wan tto make this a 32bit integer by using pipe 0 however it's erroring out
$scope.acceleration = {
x: event.accelerationIncludingGravity.x*10 | 0,
y: event.accelerationIncludingGravity.y*10 | 0,
z: event.accelerationIncludingGravity.z*10 | 0
};

$scope.$digest();

};
}
});

HTML:

<div ng-app="morningharwoodApp" ng-controller="MainCtrl">
<div class="wrap">
<div class="cube">
<div class="icon-wrapper">
<div class="icons" ng-repeat="(key, val) in squares">
<p>X : <span>{{acceleration.x}}</span></p>
<p>Y : <span>{{acceleration.y}}</span></p>
<p>Z : <span>{{acceleration.z}}</span></p>
</div>
</div>
</div>

</div>

</div>

最佳答案

为什么要使用按位运算符,有一个方法 toFixed 可以做到这一点。它允许您指定小数点后的位数

var d = 5.231579843214564;
var fixed = d.toFixed(2);
console.log(fixed);
//outputs: 5.23

请注意,这会创建一个字符串表示形式,如果您希望它返回数字而不是字符串,请在前面添加 + 运算符

var fixed = +d.toFixed(2);

关于javascript - 在 javascript 中使用按位删除小数的语法帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24975245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com